gpt4 book ai didi

javascript - 从对象数组迭代对象属性

转载 作者:行者123 更新时间:2023-12-01 01:27:46 27 4
gpt4 key购买 nike

我给出了以下数组:

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

我认为这个看起来不太漂亮,所以有人有更好的解决方案作为给定的解决方案(也许在运行时也更好)?

提前致谢!

最佳答案

如果您为每个属性传递一组规则,则通常可以执行此操作,如下所示:

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

关于javascript - 从对象数组迭代对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53600026/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com