[英]Find property with value of true and return its message
Supposed I have an object of假设我有一个 object
let testObj = {
keys : {
chkkeys : false,
msg : 'test one'
},
grtr : {
chkgrtr : true,
msg : 'test two'
},
empt : {
chkEmpt : false,
msg : 'test three'
}
}
How can I find the property with a value of true and return its message如何找到值为 true 的属性并返回其消息
For example this is the only true chkgrtr: true
therefore the value should be return is 'test two'
例如,这是唯一真正的
chkgrtr: true
因此返回的值应该是'test two'
this is what I have tried so far这是我迄今为止尝试过的
Object.keys(testObj).forEach((item) => {
Object.keys(testObj[item]).forEach((sI) => {
if (testObj[item][sI] === true) {
return testObj[item]['sMsg'];
}
})
})
Take the Object.values
of the testObj
, .find
the one with a property, other than msg
, which has a value of true
, and return its msg
:取
Object.values
的testObj
, .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); }
This is a pretty weird object structure, though.不过,这是一个非常奇怪的 object 结构。 If at all possible, it'd probably be better to change it so that all keys are the same, while only changing the values.
如果可能的话,最好更改它以使所有键都相同,而只更改值。 Eg, the objects could be
例如,对象可以是
empt: {
chk: false,
name: 'empt', // put the variable key here, if you actually need it
msg: 'test three'
}
Then all you have to do is .find(obj => obj.chk)
.那么你所要做的就是
.find(obj => obj.chk)
。
Just use Array.prototype.find
instead of forEach
.只需使用
Array.prototype.find
而不是forEach
。 that would solve it for you.那会为你解决它。
Object.keys(testObj).find((item) => {
return Object.keys(testObj[item]).find((sI) => {
if (testObj[item][sI] === true) {
return testObj[item]['sMsg'];
}
})
})
Few things you here are:你在这里的几件事是:
forEach
forEach
typo
the key is msg
not sMsg
in testObj
sMsg
了关键是msg
而不是typo
中的testObj
Try this:尝试这个:
let testObj = { keys: { chkkeys: false, msg: 'test one' }, grtr: { chkgrtr: true, msg: 'test two' }, empt: { chkEmpt: false, msg: 'test three' } } let res = ""; Object.keys(testObj).forEach((item, val) => { Object.keys(testObj[item]).forEach((sI) => { if (testObj[item][sI] === true) { res = testObj[item]['msg']; } }) }) console.log(res);
**Object.entries()** May help you in this case.
let testObj = {
keys : {
chkkeys : false,
msg : 'test one'
},
grtr : {
chkgrtr : true,
msg : 'test two'
},
empt : {
chkEmpt : false,
msg : 'test three'
}
}
let Entries = Object.entries(testObj);
for(var i = 0; i<Entries.length; i++){
if(Object.entries(Entries[i][1])[0][1]===true){
console.log(Entries[i])
}
}
Functional way:功能方式:
Object.values(testObj).find(value=> value[Object.keys(value).find(key=>key != 'msg')]).msg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.