Javascript 确定数组中的所有对象是否都有匹配的参数

Javascript 确定数组中的所有对象是否都有匹配的参数,javascript,Javascript,我有一个对象数组 [ { email: 'john@example.com', name: 'John Doe' }, { email: 'john@example.com', name: 'John Doe' }, { email: 'john@example.com', name: 'John Doe' }, { email: 'Johnny@ex

我有一个对象数组

[
    {
      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( all objects.email match ) {
     // they are all the same
} else {
    // They are not the same
}
如果您需要查看集合中是否存在多个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,那么这就有点复杂了。使用与上述相同的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}`);
  }
});
使用Array.prototype.every就像Jaromonda说的那样,您可以这样做:

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
}
使用Array.prototype.every就像Jaromonda说的那样,您可以这样做:

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
}
如果所有对象属性电子邮件匹配什么?如果所有对象属性电子邮件都匹配,您需要什么?看来你需要