有一个对象包含具有这种形式的对象:
bigObject: {
"a - values": { atr: true}
"a - items": { atr: true}
"a - others": { atr: false}
"b - values": { atr: true}
"b - items": { atr: true}
"b - others": { atr: false}
"c - values": { atr: false}
"c - items": { atr: true}
"c - others": { atr: false}
}
我在函数中使用此对象来检查每次属性之一更改其 bool 值时:onButtonClicked(item)
它做了类似的事情:
onButtonClicked(item) {
bigObject[item.id].atr= !bigObject[item.id].atr;
}
在这个函数中,我想拆分它们以便能够检查以 a
、b
和 c
开头的对象的值> 分别。为此我做了:const toCheck = item.id.split("-")[0];
这很好用,如果单击了一个对象,它将只获取以 a 开头的对象。
下一步是检查特定字母是否同时存在 true
和 false
属性。
为此我试着这样做:
let countFalse = 0;
let countTrue = 0;
bigObject.forEach(x => {
if ((x.split("-")[0]) === toCheck) {
if (x.atr) {
countTrue++;
} else countFalse++;
}
if (countTrue && countFalse) {
console.log("has both true and false attributes");
} else console.log("nope");
});
所以我拆分原始名称以摆脱 (values, items, others) 然后我尝试计算 true 和 false 属性。如果两者都存在,则显示一条消息,否则,否。
出了点问题,但我不明白是什么。有什么想法吗?
最佳答案
您可以通过 ' - '
而不是 '-'
拆分来迭代条目。
var bigObject = { "a - values": { atr: true }, "a - items": { atr: true }, "a - others": { atr: false }, "b - values": { atr: true }, "b - items": { atr: true }, "b - others": { atr: false }, "c - values": { atr: false }, "c - items": { atr: true }, "c - others": { atr: false } },
countFalse = 0,
countTrue = 0,
toCheck = 'a';
Object.entries(bigObject).forEach(([k, v]) => {
if (k.split(" - ")[0] !== toCheck) {
return;
}
if (v.atr) {
countTrue++;
} else {
countFalse++;
}
});
if (countTrue && countFalse) {
console.log("has both true and false attributes");
} else {
console.log("nope");
}
一个更紧凑的版本,带有一个用于计数的对象。
var object = { "a - values": { atr: true }, "a - items": { atr: true }, "a - others": { atr: false }, "b - values": { atr: true }, "b - items": { atr: true }, "b - others": { atr: false }, "c - values": { atr: false }, "c - items": { atr: true }, "c - others": { atr: false } },
count = { false: 0, true: 0 },
toCheck = 'a';
Object.entries(object).forEach(([k, { atr }]) => count[atr] += k.startsWith(toCheck));
if (count.true && count.false) {
console.log("has both true and false attributes");
} else {
console.log("nope");
}
console.log(count);
关于javascript - 循环对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52004693/