I have two arrays of objects. example
data1 = [{
foo: '2',
box: 'yes',
id: '1234'
}, {
foo: '34',
box: 'no',
id: '1235'
}];
data2 = [{
key: 'value',
key: 'value',
id: '1234'
}, {
key: 'value',
key: 'value',
id: '1235'
}];
I need it like this based on matching id value : each obj has a unique key id, that much the second array.
finalData = [{
foo: '2',
box: 'yes',
id: '1234',
key: 'value',
key: 'value'
}, {
box: '34',
box: 'no',
id: '1235',
key: 'value',
key: 'value'
}];
basically merging the two arrays of objects based on key id .
Use Object.assign for this so that you can combine the array with the common id value, use find having condition that compares the id of both the objects.
var data1 =[ {foo:'2',box:'yes',id:'1234'},{foo:'34',box:'no',id:'1235'} ];
var data2 =[{key:'value',key2:'value2', id:'1234'},{key:'value',key2:'value2', id:'1235'}];
data1.map(x => Object.assign(x, data2.find(y => y.id == x.id)));
console.log(data1);
Since you have same key name multiple times which is ignored by the JSON object so I have taken a new property name
key2for this example.
building on @Ankit answer, you can use the spread operator too !! something like this
var data1 =[ {foo:'2',box:'yes',id:'1234'},{foo:'34',box:'no',id:'1235'} ];
var data2 =[{key:'value',key2:'value2', id:'1234'},{key:'value',key2:'value2', id:'1235'}];
const arr = data1.map(x => ({ ...x, ...data2.find(y => y.id == x.id)}));
console.log(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With