[英]Filter array of objects by another object's values
I would like to filter an array of objects based on the values in another object.我想根据另一个 object 中的值过滤对象数组。 I am trying to map()
the array and filter()
inside the function so that I am able to get a new array with only the desired (active) fields.我正在尝试在 function 中map()
数组和filter()
,以便我能够获得一个只有所需(活动)字段的新数组。
I am trying to get the filter on the Object.entries()
, I try to compare the keys and check if the values of the active filters are true
, but I am not getting it right.我正在尝试获取Object.entries()
上的过滤器,我尝试比较键并检查有源过滤器的值是否为true
,但我没有做对。
const records = [ { id: 1, name: "first", date: "05/02" }, { id: 2, name: "second", date: "06/02" }, { id: 3, name: "third", date: "07/02" }, { id: 4, name: "fourth", date: "08/02" } ]; const active = { id: true, name: false, date: true }; const result = records.map((record) => { return Object.entries(record).filter((entry) => { Object.entries(active).forEach((activeEntry) => { return activeEntry[1] && activeEntry[0] === entry[0]; }); }); }); console.log(result);
This is the desired outcome这是期望的结果
const desiredOutcome = [
{
id: 1,
date: "05/02"
},
{
id: 2,
date: "06/02"
},
{
id: 3,
date: "07/02"
},
{
id: 4,
date: "08/02"
}
];
You can filter over the entries of the object and convert it back to an object with Object.fromEntries
.您可以过滤 object 的条目并将其转换回 object 与Object.fromEntries
。
const records=[{id:1,name:"first",date:"05/02"},{id:2,name:"second",date:"06/02"},{id:3,name:"third",date:"07/02"},{id:4,name:"fourth",date:"08/02"}]; const active = { id: true, name: false, date: true }; const res = records.map(x => Object.fromEntries( Object.entries(x).filter(([k])=>active[k]))); console.log(res);
Simply filter the keys by the key existing and then use Object.fromEntries
to go back to an object只需按现有密钥过滤密钥,然后使用Object.fromEntries
到 go 回到 object
const records = [ { id: 1, name: "first", date: "05/02" }, { id: 2, name: "second", date: "06/02" }, { id: 3, name: "third", date: "07/02" }, { id: 4, name: "fourth", date: "08/02" } ]; const active = { id: true, name: false, date: true }; const result = records.map((record) => { return Object.fromEntries( Object.entries(record).filter(([key,value]) => active[key])); }); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.