Prabhu
Prabhu

Reputation: 13335

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

Upvotes: 1

Views: 820

Answers (2)

Ram
Ram

Reputation: 144689

You can use the .pick method:

_.pick(myItems, _.keys(ACCEPTABLE_ITEMS))

Essentially, myItems property names could be lowercase. How can I modify this to still make it work?

If you want to ignore the cases, one option is:

const keys = _.map(ACCEPTABLE_ITEMS, (_, key) => key.toLowerCase() );
_.pickBy(myItems, (_, key) => _.includes(keys, key.toLowerCase()) );

Upvotes: 3

Ajay Narain Mathur
Ajay Narain Mathur

Reputation: 5466

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>

Upvotes: 3

Related Questions