Sometimes, we want to check if an object value exists within a JavaScript object array and if not, add a new object into the array.
In this article, we’ll look at how to check if an object value exists in an array and insert a new entry if it doesn’t exist.
Using the Array.prototype.some Method
We can use the some
JavaScript method to check if an entry with the given condition exists in a JavaScript array.
And we can use the push
method to add a new entry into the array.
To use it to check if an entry with the given condition exists and add an entry if it doesn’t exist, we can write:
const arr = [{
id: 1,
username: 'fred'
}, {
id: 2,
username: 'bob'
}, {
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];
}
const newArr1 = add(arr, 'ted')
const newArr2 = add(arr, 'james')
console.log(newArr1);
console.log(newArr2);
We have the arr
array which we want to check if an entry with the given username
exists and add a new entry with the given username
if it doesn’t.
To do this, we create the add
function that takes the arr
array to check and the name
to look up.
In the function, we get the length
of arr
and set the id
to length + 1
.
Then we call arr.some
with a callback that returns whether the el
array entry meets the condition el.username === name
and assign the result to found
If found
is false
, that means an entry with username
equal to the name
doesn’t exist.
And so we call arr.push
with a new entry with the given name
as the username
.
Then we return a copy of arr
to make sure we don’t modify the original arr
array.
Therefore, newArr1
is:
[
{
"id": 1,
"username": "fred"
},
{
"id": 2,
"username": "bob"
},
{
"id": 3,
"username": "ted"
}
]
And newArr2
is:
[
{
"id": 1,
"username": "fred"
},
{
"id": 2,
"username": "bob"
},
{
"id": 3,
"username": "ted"
},
{
"id": 4,
"username": "james"
}
]
Conclusion
We can use the some
JavaScript method to check if an entry with the given condition exists in a JavaScript array.
And we can use the push
method to add a new entry into the array.