I need help merging two arrays based on ID and flattening one of the objects. I haven't been able to find a solution for my specific case.
This is what I'm attempting and what I've managed to achieve so far:
const a = {
someProperty: 'something',
anotherProperty: 'somethingelse',
listOfUsers: [
{ id: 100, a1: 'somea1', a2: 'somea2'},
{ id: 101, a1: 'somea1', a2: 'somea2'},
{ id: 102, a1: 'somea1', a2: 'somea2'},
{ id: 103, a1: 'somea1', a2: 'somea2'}
]
}
const b = [
{ id: 100, b1: { b2: 'someB2', b3: 'someB3'}},
{ id: 101, b1: { }},
{ id: 102, b1: { b2: undefined, b3: 'someB3'}},
{ id: 103, b1: { b2: 'someB2', b3: 'someB3'}}
]
const aAndB = a.listOfUsers.map(item => ({
...item,
b_role: { ...b.find((itemInner) => itemInner.id === item.id) }
}));
The result I currently get is:
{
id: 100, a1: 'somea1', a2: 'somea2',
b_role: {b2: 'someB2', b3: 'someB3'}
}
{
id: 100, a1: 'somea1', a2: 'somea2',
b_role: {}
}
However, my desired output is:
{
id: 100, a1: 'somea1', a2: 'somea2',
b_role: 'someB2'
}
{
id: 100, a1: 'somea1', a2: 'somea2',
b_role: undefined
}
Is there a way to achieve this? I am open to using underscore if it can help.