需求:
如果我有以下对象数组:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
有没有办法循环遍历数组,以检查特定的用户名值是否已经存在,如果它什么都不做,但是如果它没有用所述用户名(和新的ID)将新对象添加到数组?
解决
方法 一:
我假设id s在这里是独一无二的。 some是检查数组中事物存在的一个很好的函数:文章来源:https://www.toymoban.com/news/detail-671546.html
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'));
方法二:
这里我使用了带有.filter的ES6箭头功能来检查是否存在新添加的用户名。文章来源地址https://www.toymoban.com/news/detail-671546.html
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);
到了这里,关于检查Javascript对象数组中是否存在对象值,如果没有向数组添加新对象的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!