Aleksey Trofimenko
Aleksey Trofimenko

Reputation: 17

Merging two arrays into one that has the same amount of objects

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

Answers (2)

Nina Scholz
Nina Scholz

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

Faly
Faly

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

Related Questions