Check if object value exists within a Javascript array of objects and if not add a new object to array
I've assumed that id
s 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'));
It's rather trivial to check for existing username:
var arr = [{ id: 1, username: 'fred' },
{ id: 2, username: 'bill'},
{ id: 3, username: 'ted' }];
function userExists(username) {
return arr.some(function(el) {
return el.username === username;
});
}
console.log(userExists('fred')); // true
console.log(userExists('bred')); // false
But it's not so obvious what to do when you have to add a new user to this array. The easiest way out - just pushing a new element with id
equal to array.length + 1
:
function addUser(username) {
if (userExists(username)) {
return false;
}
arr.push({ id: arr.length + 1, username: username });
return true;
}
addUser('fred'); // false
addUser('bred'); // true, user `bred` added
It will guarantee the IDs uniqueness, but will make this array look a bit strange if some elements will be taken off its end.
This small snippets works for me..
const arrayOfObject = [{ id: 1, name: 'john' }, {id: 2, name: 'max'}];
const checkUsername = obj => obj.name === 'max';
console.log(arrayOfObject.some(checkUsername))