I have an multidimensional array with objects in it..How can I flatten it
myarr[0] =[{"name":"john","age":"50","location":"san diego"}
,{"name":"jane","age":"25","location":"new york"}
,{"name":"susane","age":"10","location":"los angeles"}
];
myarr[1] =[{"smoker":"yes","drinker":"no","insured":"no"}
,{"smoker":"no","drinker":"no","insured":"yes"}
,{"smoker":"no","drinker":"yes","insured":"no"}
];
myarr[1] =[{"status":"married","children":"none"}
,{"status":"unmarried","children":"one"}
,{"status":"unmarried","children":"two"}
];
mu is too short
436k71 gold badges863 silver badges822 bronze badges
1 Answer 1
I think this is what you're trying to do.
First you want a simple helper function to merge two objects:
function merge(a, b) {
a = a || { };
for(var k in b)
if(b.hasOwnProperty(k))
a[k] = b[k];
return a;
}
Then you can just loop through your array of arrays to merge the objects:
var flat = [ ];
for(var i = 0; i < myarr.length; ++i)
for(var j = 0; j < myarr[i].length; ++j)
flat[j] = merge(flat[j], myarr[i][j]);
And then sort it:
flat.sort(function(a, b) {
a = a.location;
b = b.location;
if(a < b)
return -1;
if(a > b)
return 1;
return 0;
});
Demo (run with your JavaScript console open): http://jsfiddle.net/ambiguous/twpUF/
References:
answered Oct 28, 2011 at 5:39
mu is too short
436k71 gold badges863 silver badges822 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
concathere.