假设我有一个对象
let testObj = {
keys : {
chkkeys : false,
msg : 'test one'
},
grtr : {
chkgrtr : true,
msg : 'test two'
},
empt : {
chkEmpt : false,
msg : 'test three'
}
}
如何找到值为 true 的属性并返回其消息
例如这是唯一正确的 chkgrtr : true
因此返回的值应该是 'test two'
这是我目前的尝试
Object.keys(testObj).forEach((item) => {
Object.keys(testObj[item]).forEach((sI) => {
if (testObj[item][sI] === true) {
return testObj[item]['sMsg'];
}
})
})
最佳答案
取testObj
的Object.values
,.find
有属性的,不是msg
,其值为 true
,并返回其 msg
:
let testObj = {
keys: {
chkkeys: false,
msg: 'test one'
},
grtr: {
chkgrtr: true,
msg: 'test two'
},
empt: {
chkEmpt: false,
msg: 'test three'
}
};
const foundObj = Object.values(testObj)
.find(obj => Object.entries(obj)
.some(([key, val]) => key !== 'msg' && val)
);
if (foundObj) {
console.log(foundObj.msg);
}
不过,这是一个非常奇怪的对象结构。如果可能的话,最好更改它,以便所有键都相同,同时仅更改值。例如,对象可以是
empt: {
chk: false,
name: 'empt', // put the variable key here, if you actually need it
msg: 'test three'
}
然后你所要做的就是.find(obj => obj.chk)
。
关于javascript - 查找值为 true 的属性并返回其消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58813418/