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