如何以更有说服力的方式说出来,最好是使用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;
应该给我:
emptyArray = ['a']
答案 0 :(得分:1)
您可以从largeArray
获取intersection(),从anObject
变量获取keys()来完成此操作。
_.intersection(largeArray, _.keys(anObject));
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;
答案 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)