[英]Get all truthy values from an array of objects
I want to get all truthy values from an array of objects:我想从对象数组中获取所有真实值:
const users = [{ name: 'string', val: false, }, { name: true, val: [], } ] const identifiers = users.map(i => Object.entries(i)) const active = identifiers.filter(function(id) { const t = id.map((i, k) => id[k][1]) return t }) console.log(active)
The idea of the code above at the end to use Object.fromEntries()
and to get something like this:最后上面代码的想法是使用
Object.fromEntries()
并得到这样的东西:
const users = [{ name: 'string, }, { name: true, } ]
At the moment i am blocked and i can't get the expected values.目前我被阻止了,我无法获得预期值。 Who can help to get the expected result?
谁能帮助获得预期的结果?
You can use Object.fromEntries
to create an object using just the properties that are truthy :您可以使用
Object.fromEntries
来创建 object ,仅使用以下属性:
const users = [{ name: true, val: false, }, { name: true, val: true, } ] const identifiers = users.map(e => { // Map User array return Object.fromEntries( // return new object for every element Object.entries(e).filter((o) => o[1] === true) // object constructed using just truthy values by filtering object o[1] -> value ) }); console.log(identifiers)
Or a beautiful one liner:或者一个漂亮的衬里:
const identifiers = users.map(e => Object.fromEntries(Object.entries(e).filter(([_,o]) => o)));
You can use reduce
method with Object.entries
and Object.fromEntries
您可以对
Object.entries
和Object.fromEntries
使用reduce
方法
let result = users.reduce((acc,i) => {
let obj = Object.entries(i).filter(([k,v]) => v);
acc.push(Object.fromEntries(obj));
return acc;
}, [])
console.log(result);
You can decompose, filter and reconstruct the objects like this:您可以像这样分解、过滤和重建对象:
const users = [{name:true,val:false,},{name:true,val:[],dd:0,ee:1,ff:[0,1]}], res = users.map(i => Object.fromEntries(Object.entries(i).filter(([_,v])=>.Array.isArray(v)&&v || v.length)) ) console.log(res)
This should do the trick:这应该可以解决问题:
const newData = users.map(user => {
return Object.keys(user).reduce((obj, key) => {
if (user[key]) { //for strict truthy, make user[key] === true
obj[key] = user[key];
}
return obj;
} ,{});
});
That will:这将:
Note that this will return a new structure, not modify the existing one.请注意,这将返回一个新结构,而不是修改现有结构。 I saw the update to the question and put a comment in the code accordingly.
我看到了问题的更新,并相应地在代码中添加了评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.