我有一個如下所示的陣列。
cont arr= [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
我能知道如何驗證陣列物件中是否存在“用戶名”嗎?
uj5u.com熱心網友回復:
hasOwnProperty可以用于那個
let x = {
y: 1
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false
有關更多資訊,請參閱SO 相關問題
uj5u.com熱心網友回復:
如果你想知道陣列中是否存在特定的用戶名值,你可以使用Array.some()它
const arr= [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
const checkName = (arr,name) => arr.some(a => a.username === name)
console.log(checkName(arr,'bill'))
console.log(checkName(arr,'billA'))
如果只是想檢查陣列中是否存在用戶名屬性,我們可以結合Object.keys()、Array.flat()和Array.includes()來做
const arr= [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
const checkName = (arr,name) => arr.map(a =>Object.keys(a)).flat().includes(name)
console.log(checkName(arr,'username'))
console.log(checkName(arr,'username1'))
uj5u.com熱心網友回復:
const arr = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ];
// get array of usernames from array of objects
const usernames = arr.map(obj => obj.username);
console.log(usernames);
console.log(usernames.includes('bill'));
console.log(usernames.includes('paul'));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537342.html
