使用lodash

时间:2016-11-28 22:46:14

标签: javascript lodash

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

myItems可能如下所示:

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

我想过滤掉myItems,以便它只包含ACCEPTABLE_ITEMS中提到的属性。我怎么能用lodash做到这一点?

我尝试过这样的事情,但我认为这不对:

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

2 个答案:

答案 0 :(得分:3)

您可以使用.pick方法:

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

基本上,myItems属性名称可以是小写的。如何修改它仍然可以使它工作?

如果您想忽略这些案例,可以选择一个选项:

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

答案 1 :(得分:3)

您可以使用pickBy

工作片段: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>
&#13;
&#13;
&#13;

更新

使条件不区分大小写(部分)

&#13;
&#13;
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);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
&#13;
&#13;
&#13;