0

I have two arrays of objects

const obj = {
    teamRows: [
        {name: 'Adam', admin_id: 3},
        {name: 'Bob', admin_id: 4},
        {name: 'Ivan', admin_id: 5},
    ],
    roleRows: [
        {title: 'Lead Bizdev', role_id: 5},
        {title: 'Lead', role_id: 6},
        {title: 'Integration', role_id: 7},
    ]
};

I want to get something like this. Each row in teamRows is equal of row in roleRows

const newArr = [
    {name: 'Adam', admin_id: 3, title: 'Lead Bizdev', role_id: 5},
    {name: 'Bob', admin_id: 4, title: 'Lead', role_id: 6},
    {name: 'Ivan', admin_id: 5, title: 'Integration', role_id: 7},
]
  • Possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – pishpish Oct 05 '19 at 09:14

2 Answers2

0

Assuming the length of each array is equal, a simple solution based on Array#map would be:

const obj = {
    teamRows: [
        {name: 'Adam', admin_id: 3},
        {name: 'Bob', admin_id: 4},
        {name: 'Ivan', admin_id: 5},
    ],
    roleRows: [
        {title: 'Lead Bizdev', role_id: 5},
        {title: 'Lead', role_id: 6},
        {title: 'Integration', role_id: 7},
    ]
};


// For each teamRow, map it to a new object that is the merged
// result of teamRow and the corresponding roleRow (by index)
const newArr = obj.teamRows.map((teamRow, index) => 
    ({ ...teamRow, ...obj.roleRows[index] }))

console.log(newArr);
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
0

You could reduce all values of the object.

const
    object = { teamRows: [{ name: 'Adam', admin_id: 3 }, { name: 'Bob', admin_id: 4 }, { name: 'Ivan', admin_id: 5 },], roleRows: [{ title: 'Lead Bizdev', role_id: 5 }, { title: 'Lead', role_id: 6 }, { title: 'Integration', role_id: 7 }] },
    result = Object
        .values(object)
        .reduce((a, b) => a.map((o, i) => Object.assign({}, o, b[i])));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392