如果我有以下对象数组:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
有没有一种方法可以遍历数组以检查特定的用户名值是否已经存在,如果它什么都不做,但如果不存在则使用所述用户名(和新 ID)将新对象添加到数组中?
谢谢!
最佳答案
我假设 id
在这里是唯一的。 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'));
关于javascript - 检查对象值是否存在于 Javascript 对象数组中,如果不存在,则将新对象添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22844560/