Categories
JavaScript Answers

How to update if exists or add new element to array of objects with JavaScript?

Spread the love

To update if exists or add new element to array of objects with JavaScript, we can check if the index of the item that matches our condition exists.

For instance, we write

const upsert = (array, element) => {
  const i = array.findIndex((_element) => _element.id === element.id);
  if (i > -1) {
    array[i] = element;
  } else {
    array.push(element);
  }
};

const array = [
  { id: 0, name: "Apple", description: "fruit" },
  { id: 1, name: "Banana", description: "fruit" },
  { id: 2, name: "Tomato", description: "vegetable" },
];

upsert(array, { id: 2, name: "Tomato", description: "fruit" });

to define the upsert function.

In it, we call array.findIndex to find the element in array that matches the id value.

If it exists, then i is bigger than -1 and we assign the element to that index.

Otherwise, we call push to append element as the last item.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *