0

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?

Ruham
  • 749
  • 10
  • 32
  • 1
    You're setting a local reference to the new object--if you want to change the value in the array you could find the *index* of the matching element, or you could modify it in-place with a simple iteration w/ a compare. – Dave Newton Jun 22 '21 at 17:34
  • 2
    Use [`findIndex`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) instead: https://stackoverflow.com/a/49375465 – adiga Jun 22 '21 at 17:45

0 Answers0