I would like to filter an array of objects based on the values in another 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.
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.
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
.
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
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.