从对象数组迭代对象属性

时间:2018-12-03 18:50:23

标签: javascript arrays iteration

我给出了以下数组:

const myArray = [{ id: 1, isSet: true }, { id: 2, isSet: false }, ...];

实际上,我只想迭代对象的isSet属性(而不是所有属性)。我想到的最简单的解决方案是:

let isSet = false;
for (const obj of myArray) {
    for (const property in obj) {
        if (property === "isSet" && obj.hasOwnProperty(property)) {
            isSet |= obj[property];
        }
    }
}

console.log(isSet);

我认为这看起来并不漂亮,所以有人能提供比给定的解决方案更好的解决方案(在运行时也可能更好)吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

如果为每个属性传递一组规则,则可以一般地这样做,就像这样:

const myArray1 = [{ id: 1, isSet: false }, { id: 2, isSet: false }, { id: 3, isSet: false }];

// check if there is an object with id = 3, isSet = true
var conditions = {
  isSet: (obj) => obj.isSet,
  id: (obj) => obj.id === 3
};
// check if there is an object with id = 2, isSet = false
var conditions2 = {
  isSet: (obj) => !obj.isSet,
  id: (obj) => obj.id === 2
};

function testConditions(arr, conditions) {
  // .some() -- do ANY of the objects match the criteria?
  return arr.some(obj => {
    // .every() -- make sure ALL conditions are true for any given object
    return Object.keys(conditions).every(key => {
      // run comparitor function for each key for the given object
      return conditions[key](obj);
    });
  });
}

console.log(testConditions(myArray1, conditions)); // false -- no object with id = 3, isSet = true
console.log(testConditions(myArray1, conditions2)); // true -- myArray1[1] has id = 2, isSet = false

答案 1 :(得分:0)

您可以使用数组的some函数。

const myArray1 = [{ id: 1, isSet: false }, { id: 2, isSet: false }, { id: 3, isSet: false }];

let isSet1 = myArray1.some(obj => obj.isSet === true)

console.log(isSet1);

const myArray2 = [{ id: 1, isSet: false }, { id: 2, isSet: true }, { id: 3, isSet: false }];

let isSet2 = myArray2.some(obj => obj.isSet === true)

console.log(isSet2);