How to merge two array of objects in javascript -
how merge 2 array of objects in 1 array,the given array of objects below.
var arr1=[{key:2000,value:100},{key:2001,value:200},{key:3000,value:300}] var arr2=[{key1:2000,value1:100},{key1:2001,value1:200},{key1:3000,value1:300}]
expected output:
[ { "key": 2000, "value": 100, "child": [ { "key1": 2000, "value1": 100 } ] }, { "key": 2001, "value": 200, "child": [ { "key1": 2001, "value1": 200 } ] }, { "key": 3000, "value": 300, "child": [ { "key1": 3000, "value1": 300 } ] } ]
updated: other folks have mentioned, can loop through first array , assign corresponding element of second array child property of appropriate object in first array, or can use array.prototype.map
for example:
var newarray = arr1.map(function(cur, idx) { cur.child = [arr2[idx]]; return cur; });
it should noted (and other solutions mentioned) depend on both arrays containing same keys, , both sorted object key.
if you're not sure arrays sorted key, have preprocessing. can either sort both arrays first (this still fragile because there no guarantees keys in both arrays same), or like:
var secondgroupbykey = {}; (var i=0; i<arr2.length; i++) { secondgroupbykey[arr2[i].key1] = arr2[i]; }
and can safely say:
var key; (var j=0; j<arr1.length; j++) { key = arr1[j].key; if (secondgroupbykey[key] !== undefined) { arr1[j].child = [secondgroupbykey[key]]; } }
this approach safer relying on order of arrays, comes cost of iterating on both arrays instead of one. might want throw exception or bail out way if find key in arr1
that's not present in arr2
.
Comments
Post a Comment