简体   繁体   English

从对象数组迭代对象属性

[英]Iterate object properties from an object array

I have the following array given: 我有以下数组:

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

Actually I want to iterate only the isSet properties of the objects (not all properties). 实际上,我只想迭代对象的isSet属性(而不是所有属性)。 The most simple solution, which came on my mind was the following: 我想到的最简单的解决方案是:

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);

I think this one does not really look pretty, so has someone a better solution as the given one (maybe also better in runtime)? 我认为这看起来真的不是很漂亮,所以有没有比给定的解决方案更好的解决方案(在运行时也可能更好)?

Thanks in advance! 提前致谢!

You can do this generically if you pass in your set of rules for each property, like so: 如果为每个属性传递一组规则,则可以一般地执行此操作,如下所示:

 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 

You can use the some function of an array. 您可以使用数组的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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM