Home > Mobile >  How do you update an object in an array based on another array?
How do you update an object in an array based on another array?

Time:07-22

if you have two arrays with objects

const arr1 = [{id:'1',goal:'fun'},{id:2,goal:'work'}];
const arr2 = [{id: '1', salary: '$25k', {id:2,salary:'25k}];

how do you update arr1 to add another property of salary where arr1.id === arr2.id?

CodePudding user response:

try map and filter, the code sucks but it works

const arr1 = [{id:1,name:'tom'},{id:2,name:'john'}]
const arr2 = [{id:1,apd:'tomAppend'},{id:2,apd:'johnAppend'}]
arr1.map(item=>{
   item.apd = arr2.filter(item2=>item2.id===item.id)[0].apd
})

CodePudding user response:

  • Use map to iterate over each element of arr1 and return a new array.
  • When arr1 traverses, you can get the current element id, use filter to filter the arr2 element, and return an element array that matches the current element id.
  • Based on the fact that some people may not get a salary, use the optional chaining operator to obtain the salary attribute.
  • When returning, if the person does not get the salary, it will not change, and when the person gets the salary, use the spread syntax, copy the current element attribute, and add the salary attribute.

const arr1 = [
  {id: '1', goal: 'fun'},
  {id: '2', goal: 'work'},
  {id: '3', goal: 'slacker'}
];

const arr2 = [
  {id: '1', salary: '$25k'}, 
  {id: '2', salary: '$25k'}
];

const result = arr1.map(o1 => {
  const salary = arr2.filter(o2 => o2.id === o1.id)[0]?.salary;
  return salary ? {...o1, salary} : o1;
});

result.forEach(r => console.log(JSON.stringify(r)));

  • Related