jQuery / JavaScript:使用另一个数组过滤数组

时间:2013-09-19 12:09:40

标签: javascript jquery arrays filtering

假设我有两个阵列:

{First: [One, Two, Three], Second: [One, Two, Three], Third: [One, Two, Three]}

[First, Third]

现在我需要删除第一个数组中不在第二个数组中的每个键。所以 - 在这两个例子中 - 我应该留下:

{First: [One, Two, Three], Third: [One, Two, Three]}

我尝试使用$ .grep,但我无法弄清楚如何使用数组作为过滤器。需要帮助! :)

2 个答案:

答案 0 :(得分:4)

最快的方法是创建一个新对象,只复制你需要的密钥。

var obj = {First: [One, Two, Three], Second: [One, Two, Three], Third: [One, Two, Three]}
var filter = {First: [One, Two, Three], Third: [One, Two, Three]}


function filterObject(obj, filter) {
  var newObj = {};

  for (var i=0; i<filter.length; i++) {
    newObj[filter[i]] = obj[filter[i]];
  }
  return newObj;
}


//Usage: 
obj = filterObject(obj, filter);

答案 1 :(得分:3)

在不创建新对象的情况下,您可以执行的其他操作是删除属性

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