gpt4 book ai didi

javascript - 如何根据对象数组中的值过滤键

转载 作者:行者123 更新时间:2023-12-01 00:38:45 25 4
gpt4 key购买 nike

我想根据键值对中的值过滤对象。

我只想要真实的 key 。

尝试使用array.filter,但我无法找到解决方案。

例如:-

const arry = [{'fname': true}, {'lname': true}, {'country': false}];

有人可以帮助我如何提取值为 true 的键。

预期产出

['fname','lname'] as they are the only values which are true.

最佳答案

您可以减少数组,获取第一个条目的条目并检查值。如果值是真值,则按下该键。

var array = [{ fname: true }, { lname: true }, { country: false }],
keys = array.reduce((r, o) => {
var [key, value] = Object.entries(o)[0];
if (value) r.push(key);
return r;
}, []);

console.log(keys);

关于javascript - 如何根据对象数组中的值过滤键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57877392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com