There are many similar questions like this, but couldn't quite find what I was looking for. I have an array of unique objects that needs to be added a new object. Need to check by some parameters if there is a similar object in the array and replace it. If not - add it. So far, tried this:
const objects = [
{
param1: "abc",
param2: "def",
},
{
param1: "opq",
param2: "rst",
},
];
const newObject = {
param1: "abc",
param2: "uvw",
}
let existingObject = objects.find(
({ param1}) =>
param1 === "abc"
);
if (!existingObject ) {
objects.push(newObject);
} else {
existingObject = newObject;
}
This code doesn't work :/ Using .find here since I know that the objects in the array have unique params, and first found match is the object that needs to be updated. The expected outcome is that if a match if found (in this case it is), the object with param2: "def"
becomes param2: "uvw"
. If there is no match, then the newObject
is added to the array.
What am I missing here?