Home > Back-end >  Javascript : Filter result from keys
Javascript : Filter result from keys

Time:06-13

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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)];
});
  • Related