I've been struggling to figure out how to find and replace an array that matches the existing one. The issue lies with using the some
method.
Here is the current array:
let existingData = [{
id: 1,
product: 'Soap',
price: '$2'
},{
id: 2,
product: 'Sofa',
price: '$30'
},{
id: 3,
product: 'Chair',
price: '$45'
}]
And here is the incoming array:
const updateData = [{
id: 1,
product: 'Soap',
price: '$3'
},{
id: 2,
product: 'Sofa',
price: '$35'
}]
I have considered using the forEach
method, but I'm unsure of how to handle it when dealing with arrays. This has resulted in me getting stuck and unable to move forward.
const updateData = [{
id: 1,
product: 'Soap',
price: '$3'
},{
id: 2,
product: 'Sofa',
price: '$35'
}]
existingData.forEach(d=>{
if(d.id === ??? how can I match this to the incoming array?)
// If there is a match, update the existing data with the updated one.
})
The expected result should resemble this:
let existingData = [{
id: 1,
product: 'Soap',
price: '$3'
},{
id: 2,
product: 'Sofa',
price: '$35'
},{
id: 3,
product: 'Chair',
price: '$45'
}]
If, in certain cases, the data is not found in existingData, then simply add the incoming array to the existing array.
I would appreciate any guidance on how to achieve this or if there is a more efficient solution available. Thank you!