简体   繁体   English

如果值为真,如何获取对象数组的键

[英]How to get the key of an object array if the value is true

I have an object.我有一个对象。 I want to get the keys if the value is true.如果值为真,我想获取密钥。

What I have tried:我试过的:

 const data = [{superadmin: true, admin: false, user: false}] keys = Object.keys(data).filter(k => data[k]); console.log(typeof(data)); console.log(data) console.log(keys)

Expected Output:预期输出:

["superadmin"]

For the given code对于给定的代码

keys = Object.keys(data[0]).filter(k => data[0][k] === true);

should work.应该管用。

This works这有效

 const data = [{ superadmin: true, admin: false, user: false }] keys = data.map(obj => { const data = Object.keys(obj).filter((key) => { return.;obj[key] }) return data }).flat(1); console.log(keys)

Instead returning value, you simply assign the keys with a value of true to a variable, like this您只需将值为true的键分配给变量,而不是返回值,就像这样

 const data = [{superadmin: true, admin: false, user: false}] let mkeys data.map((obj) => { mkeys = Object.keys(obj).filter(k => obj[k]) }) console.log(mkeys)

This is very simple:这很简单:

let keys=[];
for (let [key, value] of Object.entries(data)){
    if (data[key]) keys.push(key)
}
console.log(keys)

If you want one line:如果你想要一行:

keys = Object.keys(data).filter(k => data[k]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM