3

I have the following array of objects which I need to convert to one object. Is there an easy way to do this? I have underscore on the page. Maybe it can help.

[{John:{name:"John", age : 59}},{Dave:{name:"Dave", age:62}}]

to

{John:{name:"John", age : 59}, Dave:{name:"Dave", age:62}}

I think I can recurse over the array and make the final object but am hoping there is a more simple/better way. Any pointers appreciated as I'm a javascript noob.

4 Answers 4

9

Since you mentioned you have Underscore.js available, all you really need is to use the extend function:

var arr = [{John:{name:"John", age : 59}},{Dave:{name:"Dave", age:62}}];

var flattened = _.extend.apply(_, arr);

http://jsfiddle.net/Yjmbk/

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

1 Comment

I just went "ooh!" to myself when that actually worked. Brilliant but odd solution +1
3
var arr = [{John:{name:"John", age : 59}},{Dave:{name:"Dave", age:62}}];

var obj = {};

for(var i = 0; i < arr.length; i++){
    for(x in arr[i]){
        obj[x] = arr[i][x];   
    }
}

http://jsfiddle.net/jp4wG/

2 Comments

thanks, will accept this as soon as it lets me. much appreciated the help.
How could we do this when the depth of the array is unknown? For eg. [{John:{children:[{Dave:{children:[{Maggie:children....
1

This should do the trick:

var names = [{John:{name:"John", age : 59}},{Dave:{name:"Dave", age:62}}];
var flattened = {};

for (var i = 0; i < names.length; i++) {
    for (var entry in names[i]) {
        flattened[entry] = names[i][entry];
    }
}

Comments

1

Most javascript frameworks (Mootools, JQuery, possibly underscore) will come with some functions that would make this easier. If the objects you are flattening are custom classes you'll have to watch out for added method definitions popping up in the for in loop.

var nested = [{John:{name:"John", age : 59}},{Dave:{name:"Dave", age:62}}], flattened = {};

for(var i = 0; i < nested.length; i++) {
    for(key in nested[i]) {
         flattened[key] = nested[i][key];  
    }
}

Comments

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.