[英]how to filter keys based on values in a array of objects
I would like to filter the object based on values in a key value pair. 我想根据键值对中的值过滤对象。
I want the keys which are only true. 我想要只有真实的键。
Tried using array.filter
but I am not able to find a solution. 尝试使用
array.filter
但我找不到解决方案。
Eg:- 例如:-
const arry = [{'fname': true}, {'lname': true}, {'country': false}];
Can someone help me how to extract keys which have the values as true. 有人可以帮助我如何提取具有真实值的键。
Expected o/p 预期o / p
['fname','lname'] as they are the only values which are true.
['fname','lname'],因为它们是唯一正确的值。
You could reduce the array, take the entry of the first entries and check the value. 您可以减少数组,获取第一个条目的条目并检查值。 Push the key, if the value is truthy.
如果值为真,请按键。
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);
Array.filter
takes a function which should return true or false, which indicates whether a particular element from an array should be retained or not. Array.filter
带有应返回true或false的函数,该函数指示是否应保留数组中的特定元素。
You have an array objects, and objects themselves can have multiple keys and values. 您有一个数组对象,并且对象本身可以具有多个键和值。 You need a multi-step process here:
您需要在这里执行一个多步骤的过程:
You can use Object.assign to merge objects. 您可以使用Object.assign合并对象。 We'll use Array.reduce to reduce the array of objects into a single object:
我们将使用Array.reduce将对象数组简化为单个对象:
const combined = arry.reduce((acc, val) => Object.assign({}, acc, val))
This will result in a single object containing all your key-value pairs: 这将导致包含所有键值对的单个对象:
// { country: false, fname: true, lname: true}
Now we just need to select the entries which have a true value, which results in an array of arrays: 现在,我们只需要选择具有真实值的条目即可生成一个数组数组:
const entries = Object.entries(combined).filter(([k, v]) => v)
// [["lname", true], ["fname", true]]
Then we can map out the keys from that array, like so: 然后,我们可以映射出该数组中的键,如下所示:
entries.map(([k, v]) => k)
// ["lname", "fname"]
These steps could all be chained together for brevity. 为了简洁起见,这些步骤都可以链接在一起。
const arry = [{'fname': true}, {'lname': true}, {'country': false}]; Object.entries(arry.reduce((acc, val) => Object.assign({}, acc, val))) .filter(([k, v]) => v) .map(([k, v]) => k)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.