0

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

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck 🙂
1
array2.forEach(i1 => {
    const index = array1.findIndex(i2 => i2.id == i1.id);
    if(index > -1) {
        array1.splice(index, 1, i1);
  }
});

3 Comments

Can you explain why this works?
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck 🙂
thanks for answer, both answer help me, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.