Categories
JavaScript Answers

How to check if object value exists within a JavaScript array of objects and if not add a new object to array?

Spread the love

To check if object value exists within a JavaScript array of objects and if not add a new object to array, we use the some method.

For instance, we write

const arr = [
  { id: 1, username: "fred" },
  { id: 2, username: "bill" },
  { id: 3, username: "ted" },
];

const add = (arr, name) => {
  const { length } = arr;
  const id = length + 1;
  const found = arr.some((el) => el.username === name);
  if (!found) {
    arr.push({ id, username: name });
  }
  return arr;
};

console.log(add(arr, "ted"));

to define the add function.

Then we check if the entry with username equal to name exists with some.

If it returns false, then we call arr.push to append the object into the arr array.

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 *