1

What is the best way to convert:

{
 0: 'a',
 1: 'b',
 2: 'c'
},
 {
 0: 'd',
 1: 'e',
 2: 'f'
}

to:

[ [a [b,c] ], [d [e,f] ] ]

where the 0 property of objects have the array of 1 and 2 objects? Is there a way to do that? Thanks

1 Answer 1

1

Try to use map method:

var data = [{
    0: 'a',
    1: 'b',
    2: 'c'
}, {
    0: 'd',
    1: 'e',
    2: 'f',
    3: 'g'
}];

var result = data.map(function (obj) {
    var subArr = Object.keys(obj).slice(1).map(function(key) {
        return obj[key];
    });
    return [obj[0], subArr];
});

alert(JSON.stringify(result, null, 4));

Above function use the element at index 0 as the first item of the nested arrays, and everything else in the subarray.

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

6 Comments

hi, what if I have thousands of data objects. ? It means I need to map them 1 by 1?
You mean that you can have not 3 but arbitrary number of elements in nested objects?
Check generic implementation.
Can I ask you some. Is there any other way to do it without using map function?
Yes, you can loop with for (var key in obj) { subArr.push(obj[key]) }.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.