【发布时间】:2022-11-21 17:01:20
【问题描述】:
我有一个如下所示的数组。
cont arr= [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
我能知道如何验证数组对象中是否存在“用户名”吗?
【问题讨论】:
标签: javascript arrays arrayobject
我有一个如下所示的数组。
cont arr= [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
我能知道如何验证数组对象中是否存在“用户名”吗?
【问题讨论】:
标签: javascript arrays arrayobject
hasOwnProperty 可用于此
let x = {
y: 1
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false
更多信息请参考SO related question
【讨论】:
arr.hasOwnProperty("username") == false jsfiddle.net/j13kapcn
如果你想知道数组中是否存在特定的用户名值,你可以使用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'))
【讨论】:
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'));
【讨论】: