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

214
Views
Javascript : Filter result from keys

I have the below object:

var colors = {
    key1:"Red",
    key2:"Blue",
    key3:"Green",
    key4:"Black"
}

I also have this array of keys:

var keys = ["key1","key3","key4"]

I want to fetch the corresponding colors from colors. For that, I have written code -

keys.map((key)=>{
    var color= colors.filter(x=>x==key);
});

But I am getting error here -

colors.filter is not a function
about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

To extract each of the keys, map is the correct option but you just need to fetch the corresponding value from colors:

var colors=
{
  key1:"Red",
  key2:"Blue",
  key3:"Green",
  key4:"Black"
};
var keys = ["key1", "key3", "key4"];

const result = keys.map(key => colors[key]);

console.log(result);

Note that if a key doesn't exist, the value output is undefined. To remove undefined values append .filter(Boolean) at the end (thanks Roko C. Buljan):

const result = keys.map(key => colors[key]).filter(Boolean);

Your issue was you were trying to run filter on an object. filter is not a method on objects, instead it's an array. If you want to use filter, one option is to use Object.entries like so (but the solution above is far simpler).

var colors=
{
  key1:"Red",
  key2:"Blue",
  key3:"Green",
  key4:"Black"
};
var keys = ["key1", "key3", "key4"];

const result = Object.entries(colors).filter(([key, color]) => keys.includes(key)).map(([, color]) => color);

console.log(result);

about 4 years ago · Santiago Gelvez Report

0

Please try the following:

var colors = {
  key1:"Red",
  key2:"Blue",
  key3:"Green",
  key4:"Black"
}
    
var keys = ["key1","key3","key4"]
    
let a = keys.map((key)=>{
  return colors[Object.keys(colors).filter(x=>x==key)];
});
about 4 years ago · Santiago Gelvez Report

0

You could use Array.prototype.reduce()

const colors = {
  key1:"Red",
  key2:"Blue",
  key3:"Green",
  key4:"Black"
};
const keys = ["key1", "key3", "key4", "key99"];

const result = keys.reduce((a, k) => (colors[k]&&a.push(colors[k]), a), []);

console.log(result)

notice that the "key99" will not be included in the result Array

about 4 years ago · Santiago Gelvez 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!