Reputation: 21
How to merge the two array of objects in one array,the given array of objects like 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
}
]
}
]
Upvotes: 2
Views: 150
Reputation: 2313
If I understood correctly you need to put the n-th element of array B as a 'child' property of the object with the same index on array A; here's my attempt:
function addChildren(master, child){
return master.map(function(elem, i){
elem.child = elem.child || [];
elem.child.push(child[i]);
return elem;
});
};
Upvotes: 0
Reputation: 11895
UPDATED: As some other folks have mentioned, you can loop through the first array and assign the corresponding element of the second array to the child property of the appropriate object in the first array, or you can use Array.prototype.map
for example:
var newArray = arr1.map(function(cur, idx) {
cur.child = [arr2[idx]];
return cur;
});
It should be noted that this (and the other solutions mentioned) depend on both arrays containing the same keys, and that they are both sorted by object key.
If you're not sure that the arrays will be sorted by key, you will have to do some preprocessing. You can either sort both arrays first (this is still fragile because there are no guarantees that the keys in both arrays are the same), or do something like:
var secondGroupByKey = {};
for (var i=0; i<arr2.length; i++) {
secondGroupByKey[arr2[i].key1] = arr2[i];
}
and then you can safely say:
var key;
for (var j=0; j<arr1.length; j++) {
key = arr1[j].key;
if (secondGroupByKey[key] !== undefined) {
arr1[j].child = [secondGroupByKey[key]];
}
}
This approach is safer than relying on the order of the arrays, but it comes with the cost of iterating over both arrays instead of just one. You also might want to throw an exception or bail out another way if you find a key in arr1
that's not present in arr2
.
Upvotes: 2
Reputation: 14466
arr2.forEach(function( obj, i ) {
arr1[ i ].child = [ obj ];
});
Upvotes: 1
Reputation: 19005
Loop through the first array and and assign the corresponding value from the second array to child
of each object of the first array.
for(var i = 0;i<arr1.length;i++){
arr1[i].child=[arr2[i]];
}
Upvotes: 1