如果我有以下对象数组:
[ { 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)?
谢谢!
当前回答
这是我在@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)
其他回答
接受的答案也可以这样写,在。some上使用箭头函数
function checkAndAdd(name) {
var id = arr.length + 1;
var found = arr.some((el) => {
return el.username === name;
});
if (!found) { arr.push({ id: id, username: name }); }
}
假设我们有一个对象数组,你想检查value of name是否像这样定义,
let persons = [ {"name" : "test1"},{"name": "test2"}];
if(persons.some(person => person.name == 'test1')) {
... here your code in case person.name is defined and available
}
极大地简化了我之前的解决方案,并通过在检查指定ID是否存在之前无需遍历整个数组来提供更好的性能。
这应该是最简单的解决方案(我认为):
const users = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
const addUser = (username) => {
const user = users.find((user) => user.username === username);
if (user) return { ...user, new: false };
const newUser = {
id: users.length + 1,
username,
};
users.push(newUser);
return { ...newUser, new: true };
};
下面是一个活生生的例子:
const users = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }]; const addUser = (username) => { const user = users.find((user) => user.username === username); if (user) return { ...user, new: false }; const newUser = { id: users.length + 1, username, }; users.push(newUser); return { ...newUser, new: true }; }; // a little extra scripting here to support the input and button in the example const form = document.querySelector('form'); const input = document.querySelector('input'); const span = document.querySelector('span'); const pre = document.querySelector('pre'); const syncDataWithPre = () => { pre.innerHTML = JSON.stringify(users, null, 2); }; form.onsubmit = (e) => { e.preventDefault(); span.textContent = ''; if (input.value) { const user = addUser(input.value); const { new: isNew, ...userDetails } = user; span.classList[isNew ? 'add' : 'remove']('new'); span.textContent = `User ${isNew ? 'added' : 'already exists'}`; } input.value = ''; syncDataWithPre(); }; syncDataWithPre(); body { font-family: arial, sans-serif; } span { display: block; padding-top: 8px; font-weight: 700; color: #777; } span:empty { display: none; } .new { color: #0a0; } .existing: { color: #777; } <form> <input placeholder="New username" /> <button>Add user</button> </form> <span></span> <pre></pre>
这个小片段对我有用。
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))
你也可以试试这个
const addUser = (name) => {
if (arr.filter(a => a.name == name).length <= 0)
arr.push({
id: arr.length + 1,
name: name
})
}
addUser('Fred')