jQuery的/ JavaScript的:滤波阵列与另一个数组 [英] jQuery/JavaScript: Filter array with another array
本文介绍了jQuery的/ JavaScript的:滤波阵列与另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有两个数组:
Let's say I have two arrays:
{First: [One, Two, Three], Second: [One, Two, Three], Third: [One, Two, Three]}
[First, Third]
现在我需要删除的第一阵列每一个关键,是不是在第二个数组。所以 - 与这两个例子 - 我应该留下:
Now I need to remove every key in first array that is not in second array. So - with those two in example - I should be left with:
{First: [One, Two, Three], Third: [One, Two, Three]}
我试图用该.grep $,但我无法弄清楚如何使用数组作为过滤器。需要帮助! :)
I tried to use $.grep for that, but I can't figure out how to use array as a filter. Help needed! :)
推荐答案
您可以在不创建一个新对象做其他的事情是删除属性。
Other thing you can do without creating a new object is to delete properties
var obj = {First: ["One", "Two", "Three"], Second: ["One", "Two", "Three"], Third: ["One", "Two", "Three"]};
var filter = ["Second", "Third"];
function filterProps(obj, filter) {
for (prop in obj) {
if (filter.indexOf(prop) == -1) {
delete obj[prop];
}
};
return obj;
};
//Usage:
obj = filterObject(obj, filter);
这篇关于jQuery的/ JavaScript的:滤波阵列与另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文