代码之家  ›  专栏  ›  技术社区  ›  wake-0

从对象数组迭代对象属性

  •  0
  • wake-0  · 技术社区  · 7 年前

    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 回复  |  直到 7 年前
        1
  •  2
  •   mhodges    7 年前

    如果传入每个属性的规则集,则可以按常规执行此操作,如下所示:

    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
        2
  •  0
  •   IMTheNachoMan    7 年前

    你可以使用 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);