如何根据项目是否是对象的关键字从另一个列表创建项目列表? (Lodash首选)

时间:2016-06-28 20:22:42

标签: node.js lodash

如何以更有说服力的方式说出来,最好是使用Lodash:



anObject = {
  'a': 'apple',
  'b': 'banana'
};
largeArray = ['a', 'c', 'd'];
emptyArray = [];

for (var s = 0; s < largeArray.length; s++) {
  if (anObject[largeArray[s]]) {
    emptyArray.push(anObject[largeArray[s]]);
  }
}

console.log(emptyArray)
&#13;
&#13;
&#13;

应该给我:

emptyArray = ['a']

3 个答案:

答案 0 :(得分:1)

您可以从largeArray获取intersection(),从anObject变量获取keys()来完成此操作。

_.intersection(largeArray, _.keys(anObject));

&#13;
&#13;
var anObject = {'a': 'apple', 'b': 'banana'};
var largeArray = ['a','c','d'];

var emptyArray = _.intersection(largeArray, _.keys(anObject));

console.log(emptyArray);
&#13;
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你不需要为此付出代价。使用内置的Array.prototype.filter()方法。这将返回一个新数组而不修改原始数组。

let obj = {'a': 'apple', 'b': 'banana'};
let arr = ['a', 'c', 'd'];

let result = arr.filter(item => obj.hasOwnProperty(item));

console.log(result); // ['a']

或者,在ES5中:

var obj = {'a': 'apple', 'b': 'banana'};
var arr = ['a', 'c', 'd'];

var result = arr.filter(function(item) {
  return obj.hasOwnProperty(item);
});

console.log(result); // ['a']

答案 2 :(得分:0)

使用来自lodash的filter()has()partial()

_.filter(largeArray, _.partial(_.has, anObject));