Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
Filter an object based on values in an array

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!