EN
JavaScript - check if object exists in array and add it if not
0 points
In this article, we would like to show you how to check if object exists in array and add it if not in JavaScript.
In this example, we create a reusable arrow function that takes two arguments:
array
to which we want to add an object,name
- the new object's (user) name property.
The function uses some()
method to check if an object with a given name
already exists and adds it if not.
xxxxxxxxxx
1
const addIfNotExists = (array, name) => {
2
const id = array.length + 1;
3
const found = array.some((item) => item.username === name);
4
if (!found) array.push({ id, username: name });
5
return array;
6
};
7
8
const users = [
9
{ id: 1, username: 'Tom' },
10
{ id: 2, username: 'Ann' },
11
];
12
13
addIfNotExists(users, 'Ann'); // username already exists, object won't be added
14
addIfNotExists(users, 'Kate');
15
16
console.log(JSON.stringify(users, null, 4)); // [ { id: 1, username: 'Tom' }, { id: 2, username: 'Ann' }, { id: 3, username: 'Kate' } ]