Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an array of object a value of a object in Array in Node.js

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 .

like image 685
Navid Yousefzai Avatar asked Nov 02 '25 23:11

Navid Yousefzai


2 Answers

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 key2 for this example.

like image 152
Ankit Agarwal Avatar answered Nov 05 '25 13:11

Ankit Agarwal


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);
like image 35
tjadli Avatar answered Nov 05 '25 14:11

tjadli