Reputation: 1844
I have two arrays:
[{Name: "Jack", Depot: "5"}, {Name: "Jill", Depot: "6"}]
and
[{Depot Name: "Edgware"}, {Depot Name: "Romford"}]
I need to take the objects from the second array and merge them with the objects in the first array to produce a result of:
[{Name: "Jack", Depot: "5", Depot Name: "Edgware"}, {Name: "Jill", Depot: "6", Depot Name: "Romford"}]
Any help with this would be much appreciated
Upvotes: 0
Views: 71
Reputation: 975
var array1 = [{
Name: "Jack",
Depot: "5"
}, {
Name: "Jill",
Depot: "6"
}];
var array2 = [{
'Depot Name': "Edgware"
}, {
'Depot Name': "Romford"
}];
for (var a in array1) {
for (var p in array1[a]) {
//to esclude all possible internal properties
if (array1[a].hasOwnProperty(p)) {
array2[a][p] = array1[a][p];
}
}
}
console.log(array2);
Upvotes: 7
Reputation: 9561
Here is a solution with Object.assign()
.
P.S: Check for browser compatibility, this solution might not work in IE
var arr1 = [{
"Name": "Jack",
"Depot": "5"
}, {
"Name": "Jill",
"Depot": "6"
}];
var arr2 = [{
"Depot Name": "Edgware"
}, {
"Depot Name": "Romford"
}];
var arr1Copy = arr1;
var newArr = arr1Copy.map(function(v, i) {
return Object.assign(v, arr2[i]);
});
console.log(newArr);
Upvotes: 1