Home > Net >  Replace an object that is inside of array if object id value from another array match
Replace an object that is inside of array if object id value from another array match

Time:10-09

I have this arrays with objects that looks like this:

array1 = [
 0:{id:145, value:130000},
 1:{id:146, value:103300},
 2:{id:147, value:79500},
]

array2 = [
 0:{id:145, value:135000}
]

And I want to replace the object inside the array if the id of the object in array2 match with some id of the object in array1

So I expect something like this:

array1 = [
 0:{id:145, value:135000},
 1:{id:146, value:103300},
 2:{id:147, value:79500},
]

I have this code

array1.splice(1, 1, array2[0])

but it returns me this:

array1 = [
 0:{id:145, value:135000},
 1:{id:145, value:130000},
 2:{id:146, value:103300},
 3:{id:147, value:79500},
]

Any help I'll appreciate

CodePudding user response:

array2.forEach(i1 => {
    const index = array1.findIndex(i2 => i2.id == i1.id);
    if(index > -1) {
        array1.splice(index, 1, i1);
  }
});

CodePudding user response:

let array1 = [
 {id:145, value:130000},
 {id:146, value:103300},
 {id:147, value:79500},
]

let array2 = [
 {id:145, value:135000},
 {id:147, value:135023}
]
    array2.map(x => {
    let index = array1.findIndex(d=> d.id === x.id)
  array1[index] = x  
})
console.log(array1)

  • Related