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
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);
1 Comment
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];
}
}
2 Comments
[{John:{children:[{Dave:{children:[{Maggie:children....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
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];
}
}