javascript比较所有对象中某个键的值

时间:2018-03-08 02:26:16

标签: javascript arrays ecmascript-6

我是这样的一系列对象:

var items=
[
    {
        name: 'blah',
        country: 'Foos'
    },
    {
        name: 'foo',
        country: 'Foos'
    },
    {
        name: 'bar',
        country: 'Foos'
    },
    {
        name: 'baz',
        country: 'Foos'
    }
];

我想比较所有country键的值,如果它们都是相同的值,则返回true / false。 阵列可以是任何长度,有时只有一个对象,有时几十个。

我如何使用ecma6做法进行比较最好

更新

挑战在于我不知道keyValue每次会是什么,我只想检查该数组中所有对象是否相同。

3 个答案:

答案 0 :(得分:3)

获取第一个元素的值,然后使用every将其与其他值进行比较。every将在第一个不匹配时返回false。找到一个不匹配的ONE后,无需检查数组中的每个元素。



 let list =
[
    { name: 'foo', country: 'Foos' },
    { name: 'bar', country: 'Foos' },
    { name: 'baz', country: 'Foos' }
];


function isCountryTheSameInAllObjects(list) {
  if (!(list && list.length)) return true; // If there is no list, or if it is empty, they are all the same, aren't they?
  let compare = list[0].country;
  return list.every( item => item.country === compare);
}

console.log('is Country same?', isCountryTheSameInAllObjects(list));




如果要比较每个对象中的每个键:



let list =
[
    { name: 'foo', country: 'Foos' },
    { name: 'bar', country: 'Foos' },
    { name: 'baz', country: 'Foos' }
];

function isAllKeysTheSameInEveryObject(list) {
  if (!(list && list.length)) return true; // If there is no list, or if it is empty, they are all the same, aren't they?
  let compare = list[0];
  let sourceKeys = compare && Object.keys(compare);
  return list.every( item => {
    if ( compare ) {
      if (!item) return false;
      let itemKeys = Object.keys(item);
      // If key lenghs different, then it is not same.
      if ( sourceKeys.length != itemKeys.length) return false;
      // make sure all keys are the same.
      if ( !sourceKeys.every( key => itemKeys.indexOf(key) >= 0 )) return false;
      // compare keys
      return sourceKeys.every( key => compare[key] === item[key] );
    } else {
      // If compare is an object, but not item, then it is false.
      if (item) return false;
    }
  })
}

console.log('is all keys same?', isAllKeysTheSameInEveryObject(list));




答案 1 :(得分:1)

也可以这样做:

var items = [{
        name: 'blah',
        country: 'Foos'
    },
    {
        name: 'foo',
        country: 'Foos'
    },
    {
        name: 'bar',
        country: 'Foos'
    },
    {
        name: 'baz',
        country: 'Foos'
    }
];

function compareCountries(items) {
    for (var i = 1; i < items.length; i++) {
        if (items[i].country !== items[0].country) {
            return false;
        }
    }
    return true;
}
alert(compareCountries(items));

答案 2 :(得分:0)

我会这样推荐

首先获取第一个项目的国家/地区,然后在项目中搜索不等于

function allSame(items){
    let firstItemCountry = items[0] && items[0].country;
    return !items.find(item => item.country !== firstItemCountry) && true;
}
console.log(allSame(items));