Home > other >  Filter an object based on values in an array
Filter an object based on values in an array

Time:03-13

I have an object that contains people's names and ages

{"John":44,"Sarah":23,"Bob":43,"Kate":65,"Bill":18}

and an array that provides a list of employee names

['John', 'Bob', 'Kate', 'Bill', 'Fred']

I would like to create a new object which contains only those people and their ages that appear in both the object and array. So in this example the new object would contain

{"John":44,"Bob":43,"Kate":65,"Bill":18}

"Sarah":23 and Fred don't appear because they appear in only one of the above.

Can anyone advise on how to do this please?

CodePudding user response:

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

CodePudding user response:

simply

const 
  jso = { John: 44, Sarah: 23, Bob: 43, Kate: 65, Bill: 18 } 
, arr = [ 'John', 'Bob', 'Kate', 'Bill', 'Fred' ]
, res = arr.reduce((r,a)=>(!!jso[a]?r[a]=jso[a]:'',r),{})
  ;
console.log(res)

  • Related