Reputation: 17
need help with little thing. I've searched current question, but didn't find good example.
I have two arrays with same count of objects:
array1 = [{ id: 1, name: 'Johnny'}, { id: 2, name: 'Mike'}];
array2 = [{ hair: 'black'}, { hair: 'white'}];
I need
array3 = [
{ id: 1, name: 'Johnny', hair: 'black'},
{ id: 2, name: 'Mike', hair: 'white'}
]
I've tried several ways with push and [...ES6], but I always return 4 objects instead of 2.
Upvotes: 2
Views: 59
Reputation: 386826
You could use Array#reduce
with Array#map
and Object.assign
for an arbitrary count of arrays and map objects at same index in one object.
var array1 = [{ id: 1, name: 'Johnny'}, { id: 2, name: 'Mike'}];
array2 = [{ hair: 'black'}, { hair: 'white'}],
result = [array1, array2]
.reduce((r, a) => a.map((o, i) => Object.assign(r[i] || {}, o), []));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1
Reputation: 13356
Use Object.assign of ES6:
var array1 = [{ id: 1, name: 'Johnny'}, { id: 2, name: 'Mike'}];
var array2 = [{ hair: 'black'}, { hair: 'white'}];
var merged = array1.map((el, index) => Object.assign(el, array2[index]));
console.log(merged);
Upvotes: 5