3

I want to transform this object so that I can call it that way

cars.ox, bikes.ox

var baseValue = [
    {
        '2014-12-01': {
            'cars;ox;2014-12-01':100,
            'cars;ot;2014-12-01':150,
            'bikes;ox;2014-12-01':50,
            'bikes;ot;2014-12-01':80
        },
        '2014-12-02': {
            'cars;ox;2014-12-02':100,
            'cars;ot;2014-12-02':150,
            'bikes;ox;2014-12-02':50,
            'bikes;ot;2014-12-02':80
        }
    }
]

I try do this in many ways, but at the end i completely lost all hope.

var category = []

var obj = baseValue[0]

Object.keys(obj).forEach(function(key) {
    var dane = obj[key]
    Object.keys(dane).forEach(function(key) {
        splitted = key.split(';')
        var category = splitted[0]
        var serviceName = splitted[1];
    })
})

I would be grateful if anyone help me with this

4
  • 2
    when you call bikes.ox, what value are you hoping to get? it's hard to transform without knowing the expected outcome Commented Dec 18, 2014 at 15:01
  • What exactly is your question? Do you get an error? Don't you get the expected output? What would the expected output be? Commented Dec 18, 2014 at 15:01
  • 1
    for cars.ox i want array [100, 100] for cars.ot[150, 150] Commented Dec 18, 2014 at 15:05
  • 1
    "I try do this in many ways, but at the end i completely lost all hope." You're a developer now, kid. Commented Dec 18, 2014 at 19:22

1 Answer 1

1

I think you were close, you just need to create objects if they do not exist for the keys you want. Perhaps something like this.

var obj = baseValue[0]
var result = {};
Object.keys(obj).forEach(function(key) {
    var dane = obj[key]
    Object.keys(dane).forEach(function(key) {
        splitted = key.split(';')
        var category = splitted[0]
        var serviceName = splitted[1];
        if(!result[category]) {
            result[category] = {};
        }
        if(!result[category][serviceName]) {
            result[category][serviceName] = [];
        }

        result[category][serviceName].push(dane[key]);
    })
});

http://jsfiddle.net/6c5c3qwy/1/

(The result is logged to the console.)

Sign up to request clarification or add additional context in comments.

1 Comment

i was actually close, it's true. Thanks for help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.