Alexis
Alexis

Reputation: 51

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

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

Upvotes: 0

Views: 968

Answers (2)

Harshit Upadhyay
Harshit Upadhyay

Reputation: 159

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)

Upvotes: 1

Slev7n
Slev7n

Reputation: 371

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

Upvotes: 1

Related Questions