1

假设我有两个数组:

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

[First, Third]

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

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

我试图为此使用 $.grep ,但我不知道如何使用数组作为过滤器。需要帮助!:)

4

2 回答 2

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);
于 2013-09-19T12:19:42.857 回答
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);
于 2013-09-19T12:44:37.080 回答