[Solved] Filter an object based on values in an array [duplicate]


You can use reduce to create the result and operator in to check if the key exists:

const obj = {"John":44,"Sarah":23,"Bob":43,"Kate":65,"Bill":18};
const keys = ['John', 'Bob', 'Kate', 'Bill', 'Fred'];

const result = keys.reduce((acc, el) => {
  if (el in obj) acc[el] = obj[el];
  return acc;
}, {});

console.log(result);

Another approach is to convert the object to an array, use filter and convert the result back:

const obj = {"John":44,"Sarah":23,"Bob":43,"Kate":65,"Bill":18};
const keys = ['John', 'Bob', 'Kate', 'Bill', 'Fred'];

const result = Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key)));

console.log(result);

solved Filter an object based on values in an array [duplicate]