Prabhu Prabhu - 4 days ago 5
Javascript Question

Filter out properties using lodash

const ACCEPTABLE_ITEMS = {
APPLE: true,
ORANGE: true,
MANGO: true
};


myItems
might look like this:

{
apple: true,
orange: true,
mango: true,
grapes: true,
carrots: true
}


I want to filter out myItems so that it only includes the properties mentioned in
ACCEPTABLE_ITEMS
. How can I do this with lodash?

I tried doing something like this, but it's not right I think:

myItems = _.filter(myItems, (i) => {return ACCEPTABLE_ITEMS[i];});

A.J A.J
Answer

You can use pickBy:

Working Snippet:P

var ACCEPTABLE_ITEMS = {
  APPLE: true,
  ORANGE: true,
  MANGO: true
};

var myItems = {
  APPLE: true,
  ORANGE: true,
  MANGO: true,
  GRAPES: true,
  CARROTS: true
}

myItems = _.pickBy(myItems, function(i, key) {
  return ACCEPTABLE_ITEMS[key];
});
console.log(myItems);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

Update:

To make the condition case insensitive (partially)

var ACCEPTABLE_ITEMS = {
  APPLE: true,
  ORANGE: true,
  MANGO: true
};

var myItems = {
  apple: true,
  ORANGE: true,
  mango: true,
  GRAPES: true,
  CARROTS: true
}

myItems = _.pickBy(myItems, function(i, key) {
  return ACCEPTABLE_ITEMS[key.toUpperCase()];
});
console.log(myItems);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

Comments