我有一组对象。
xprop -id wid _NET_WM_PID
如何确定所有对象属性[
{
email: 'john@example.com',
name: 'John Doe'
}, {
email: 'john@example.com',
name: 'John Doe'
},
{
email: 'john@example.com',
name: 'John Doe'
},
{
email: 'Johnny@example.com',
name: 'John Doe'
}
]
是否匹配?基本上是这样的。
email
答案 0 :(得分:4)
var arr = [
{
email: 'john@example.com',
name: 'John Doe'
}, {
email: 'john@example.com',
name: 'John Doe'
},
{
email: 'john@example.com',
name: 'John Doe'
},
{
email: 'Johnny@example.com',
name: 'John Doe'
}
];
if (arr.every(item => item.email === 'john@example.com')) {
// all match
}
如果您需要查看集合中是否存在多于1个,则会更复杂一些。使用与上述相同的arr
:
const dict = {};
arr.forEach(item => {
if (!dict[item.email]) dict[item.email] = 0;
dict[item.email]++;
});
Object.keys(dict).forEach(email => {
if (dict[email] > 1) {
console.log(`There are more than 1 ${email}`);
}
});
答案 1 :(得分:2)
像Jaromonda一样使用Array.prototype.every
说,你可以这样做:
const arr = [
{
email: 'john@example.com',
name: 'John Doe'
}, {
email: 'john@example.com',
name: 'John Doe'
},
{
email: 'john@example.com',
name: 'John Doe'
},
{
email: 'Johnny@example.com',
name: 'John Doe'
}
]
//if the array is empty, then we consider it as matching
//make the function independent from the Array's name
if(!arr[0] || arr.every( (entry, i, array) => entry.email === array[0].email ){
//do your stuff here
}else{
//do your stuff here
}