Check if object value exists within a Javascript array of objects and if not add a new object to array

user2576960 picture user2576960 · Apr 3, 2014 · Viewed 288.9k times · Source

If I have the following array of objects:

[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

Is there a way to loop through the array to check whether a particular username value already exists and if it does do nothing, but if it doesn't to add a new object to the array with said username (and new ID)?

Thanks!

Answer

Andy picture Andy · Apr 3, 2014

I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:

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

function 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'));