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

238
Views
Return values from Obj if key in Array

I'm still learning basics of map(), filter(), forEach(), and includes() and can't seem to figure out the best way or anyway of attempting this...

Let's say I've got an arr and an obj and I need to return the object values if object key is in the array

const array = [1, 2, 3];

const object = { 1: "blue", 2: "red", 3: "green", 4: "orange", 5: "purple" };

I believe because I'm going for a new array, I need to use map()

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

0

You can use Object.entries(object) to get an array of key value pairs of the object, then filter according to the array elements, finally map and return only the values:

const array = [1, 2, 3];

const object = { 1: "blue", 2: "red", 3: "green", 4: "orange", 5: "purple" };

const result = Object.entries(object).filter(el=>array.includes(parseInt(el[0]))).map(el=>el[1])

console.log(result)

Or if you want to keep the order order of the elements (thanks to ASDFGerte), just map over the array and return the value of the element.

const array = [3,2,1];
const object = { 1: "blue", 2: "red", 3: "green", 4: "orange", 5: "purple" };

const result = array.map(el => object[el]);

console.log(result)

about 4 years ago · Juan Pablo Isaza Report

0

We will only be returning values with keys that are present in the array. So you can simply iterate through the array values, and check if there is a value in the object with the array value as the key. Since you want it to return the values from the call itself maybe we can use reduce:

let values = array.reduce((found, item) => {
    return (item in object) ? found.push(object[item]) && found : found
}, [])
console.log(values)
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!