3

if i have two arrays and i would like to rewrite "age" from arr1 with value from arr2 based on id. how would i do that?.

var arr1: [{id:1 ,name:abc , age:0 },
       {id:2 ,name:abc , age:0 }, 
       {id:3 ,name:abc , age:0 }, 
       {id:4 ,name:abc , age:0 },
       {id:5 ,name:abc , age:0 }]

var arr2:[{id:2, value: 18},{ id:4, value:20}]

expected output:

var arr1: [{id:1 ,name:abc , age:0 },
       {id:2 ,name:abc , age:18 }, 
       {id:3 ,name:abc , age:0 }, 
       {id:4 ,name:abc , age:20 },
       {id:5 ,name:abc , age:0 }]
strah
  • 6,702
  • 4
  • 33
  • 45
  • 2
    Does this answer your question? [JS/Es6 how to merge two arrays and override values in their objects](https://stackoverflow.com/questions/40566571/js-es6-how-to-merge-two-arrays-and-override-values-in-their-objects) – Fabio May 29 '21 at 20:41
  • 2
    Does this answer your question? [Merge two array of objects based on a key](https://stackoverflow.com/questions/46849286/merge-two-array-of-objects-based-on-a-key) – pilchard May 29 '21 at 20:47

3 Answers3

0

I think easiest way is like this:

arr2.forEach(x => {
    arr1.filter(y => y.id === x.id)[0].age = x.value;
});

Or:

arr2.forEach(x => {
    arr1.find(y => y.id === x.id).age = x.value;
});
-1

You can do it like this:

let arr1 = [ { id: 1, name: 'abc', age: 0 }, { id: 2, name: 'abc', age: 0 }, { id: 3, name: 'abc', age: 0 }, { id: 4, name: 'abc', age: 0 }, { id: 5, name: 'abc', age: 0 } ];
let arr2 = [ { id: 2, value: 18 }, { id: 4, value: 20 } ];

let result = arr1.map((item)=> {
  if(arr2.map((i)=>i.id).includes(item.id)) item.age = arr2.filter((i)=>i.id===item.id)[0].value;
  return item;
});

console.log('Result: ', result);
NeNaD
  • 18,172
  • 8
  • 47
  • 89
-1

As everyone is telling you, there are several ways to do it, ive added some possible simple logics of this task. Hope it will solve your problem

    var arr1 =  [{id:1 ,name:"abc" , age:0 },
       {id:2 ,name:"abc" , age:0 }, 
       {id:3 ,name:"abc" , age:0 }, 
       {id:4 ,name:"abc" , age:0 },
       {id:5 ,name:"abc" , age:0 }]

var arr2 = [{id:2, value: 18},{ id:4, value:20}]

// Method 1
for(let a = 0; a < arr1.length; a++){
  for(let b = 0; b < arr2.length; b++){
    if(arr1[a].id == arr2[b].id){
      arr1[a].age = arr2[b].value
    }
  }
}
console.log(arr1, 'updated Object')

// Method 2
arr2.forEach(a => {
  arr1.filter(b => {
    if(a.id == b.id){
        b.age = a.value
    }
  })
})

console.log(arr1)