从对象有键返回对象具有条件 true



我对对象有疑问。我想filter返回键列表,在下面的对象中条件为 true:

myObject = {
key1: {
name:"key1",
select:true
},
key2: {
name:"key2",
select:false
},
key3: {
name:"key3",
select:true
}
}

出于某种原因,我必须为其添加特定的密钥。现在我想返回一个数组有 seclecttrue.

arrayWantreturn = ["key1", "key3"]

非常感谢您的帮助。

您可以使用该对象创建循环:

var myObject = {
key1: {
name:"key1",
select:true
},
key2: {
name:"key2",
select:false
},
key3: {
name:"key3",
select:true
}
};
var arr = [];
for (var prop in myObject) {
if (myObject[prop].select) {
arr.push(myObject[prop].name);
}
}
console.log(arr);

也许您可以尝试以下方法:

const myObject = {
key1: {
name:"key1",
select:true
},
key2: {
name:"key2",
select:false
},
key3: {
name:"key3",
select:true
}
};
const result = Object.entries(myObject)
.filter(([k, v]) => v['select'])
.flatMap(e => e[1].name);
console.log(result);

我希望这有所帮助!

您可以使用Object.values()获取对象的值,然后使用.filter()保留所有selecttrue的对象。然后,可以将每个剩余对象.map()为其 name 属性,如下所示:

const myObject = { key1: { name:"key1", select:true }, key2: { name:"key2", select:false }, key3: { name:"key3", select:true } };
const res = Object.values(myObject)
.filter(({select}) => select)
.map(({name}) => name); 

console.log(res);

这使用解构赋值来提取回调方法参数中的属性值。

最新更新