1

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"
  }
];
1
  • 1. .forEach() doesn't return anything, And the return in the callback is mostly meaningless. 2. you have no return in the .filter() callback Commented May 4, 2021 at 15:19

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.