需求:
如果我有以下對(duì)象數(shù)組:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
有沒(méi)有辦法循環(huán)遍歷數(shù)組,以檢查特定的用戶名值是否已經(jīng)存在,如果它什么都不做,但是如果它沒(méi)有用所述用戶名(和新的ID)將新對(duì)象添加到數(shù)組?
解決
方法 一:
我假設(shè)id s在這里是獨(dú)一無(wú)二的。 some是檢查數(shù)組中事物存在的一個(gè)很好的函數(shù):文章來(lái)源:http://www.zghlxwxcb.cn/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箭頭功能來(lái)檢查是否存在新添加的用戶名。文章來(lái)源地址http://www.zghlxwxcb.cn/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);
到了這里,關(guān)于檢查Javascript對(duì)象數(shù)組中是否存在對(duì)象值,如果沒(méi)有向數(shù)組添加新對(duì)象的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!