如果我有以下对象数组:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
有没有办法循环遍历数组来检查特定的用户名值是否已经存在,如果它什么都不做,但如果它不使用所述用户名(和新 ID)将新对象添加到数组中?
谢谢!
如果我有以下对象数组:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
有没有办法循环遍历数组来检查特定的用户名值是否已经存在,如果它什么都不做,但如果它不使用所述用户名(和新 ID)将新对象添加到数组中?
谢谢!
我假设id
s 在这里是唯一的。some
是检查数组中事物是否存在的一个很好的函数:
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'));
检查现有用户名相当简单:
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
但是,当您必须向该数组添加新用户时,该怎么做并不是很明显。最简单的方法 - 只需推送一个id
等于的新元素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
它将保证 ID 的唯一性,但如果将某些元素从其末尾移除,则会使该数组看起来有点奇怪。
这个小片段对我有用..
const arrayOfObject = [{ id: 1, name: 'john' }, {id: 2, name: 'max'}];
const checkUsername = obj => obj.name === 'max';
console.log(arrayOfObject.some(checkUsername))
如果你有这样的元素数组,['john','marsh']
我们可以做这样的事情
const checkUsername = element => element == 'john';
console.log(arrayOfObject.some(checkUsername))
除了@sagar-gavhane的回答之外,这就是我所做的
const newUser = {_id: 4, name: 'Adam'}
const users = [{_id: 1, name: 'Fred'}, {_id: 2, name: 'Ted'}, {_id: 3, name:'Bill'}]
const userExists = users.some(user => user.name === newUser.name);
if(userExists) {
return new Error({error:'User exists'})
}
users.push(newUser)
我认为,这是解决这个问题的最短途径。这里我使用带有 .filter 的 ES6 箭头函数来检查新添加的用户名是否存在。
var arr = [{
id: 1,
username: 'fred'
}, {
id: 2,
username: 'bill'
}, {
id: 3,
username: 'ted'
}];
function add(name) {
var id = arr.length + 1;
if (arr.filter(item=> item.username == name).length == 0){
arr.push({ id: id, username: name });
}
}
add('ted');
console.log(arr);