Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

But I am getting error here –

colors.filter is not a function

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading