I'm trying to merge two objects which, both have same similar key, but different values. I want them to keep the different keys and but place them together in the matching key value
here my first obj,
const obj1 = [
{
"p_id": 1,
"name": "Peter",
"status" : "Active"
},
{
"p_id": 2,
"name": "Kane",
"status" : "Active"
},
{
"p_id": 3,
"name": "William",
"status" : "Inactive"
}
]
}
my second obj,
const obj2 = [
{ p_id: 1, type: 'home', no: '+01 234 5678' },
{ p_id: 1, type: 'work', no: '+09 111 2223' },
{ p_id: 2, type: 'home', no: '+12 345 6789' },
]
Actually I did something like this,
obj1.forEach((item) => {
Object.assign(item, {
phone: obj2.find(
(o) => o.p_id === item.p_id
)
});
});
// console.log(obj1) would be
[
{
"p_id": 1,
"name": "Peter",
"status" : "Active",
"phone" : {type: 'home', no: '+01 234 5678'}
},
{
"p_id": 2,
"name": "Kane"
"status" : "Active",
"phone" : {type: 'home', no: '+12 345 6789'}
},
{
"p_id": 3,
"name": "William"
"status" : "Inactive"
"phone" : undefined
}
]
but this is not I want. I want to be final result I need is the compare between these arrays – the final result should be like this:
const result = [
{
"p_id": 1,
"name": "Peter",
"status" : "Active",
"phone" : [
{type: 'home', no: '+01 234 5678'},
{type: 'work', no: '+09 111 2223'}
]
},
{
"p_id": 2,
"name": "Kane"
"status" : "Active",
"phone" : [
{type: 'home', no: '+12 345 6789'}
]
},
{
"p_id": 3,
"name": "William"
"status" : "Inactive"
"phone" : []
}
]
Really appreciate your kind help, Thank you!