问题描述
我有一组对象,我想检查特定的键在该组中的每个对象中是否总是具有相同的值。
这是我的简化示例:
该组的console.log。
console.log(this.groupedobjects);
..返回以下内容。
{One: {…},Two: {…},Three: {…}}
..展开时如下所示:
One: {type: "One",high: 5,medium: 0,low: 10,selected: false,…}
Two: {type: "Two",high: 56,low: 0,…}
Three: {type: "Three",high: 79,selected: false …}
我要检查键selected
是否在所有对象中都具有值false
。如果是这样,那么我想触发另一种方法。
Object.entries(this.groupedobjects).map(([key,item]) => {
if (/** Every objects key "selected" has the value "false" */) {
// trigger next method
}
});
解决方法
您可以使用数组每个方法。 JS 每个方法检查数组中的所有元素是否通过测试。如果每个选择为false,则下面的代码将返回true,并根据该结果可以执行另一个函数。
const data = {
One: { type: 'One',high: 5,medium: 0,low: 10,selected: false },Two: { type: 'Two',high: 56,low: 0,Three: { type: 'Three',high: 79,};
const ret = Object.keys(data).every((x) => !data[x].selected);
console.log(ret);
例如:
if(ret) {
//execute next function
}