最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jQueryJavaScript: Filter array with another array - Stack Overflow

programmeradmin0浏览0评论

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]}

I tried to use $.grep for that, but I can't figure out how to use array as a filter. Help needed! :)

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]}

I tried to use $.grep for that, but I can't figure out how to use array as a filter. Help needed! :)

Share Improve this question asked Sep 19, 2013 at 12:09 z-xz-x 4511 gold badge8 silver badges15 bronze badges 4
  • 1 Look, someone asked it before : stackoverflow./questions/10927722/… – BENARD Patrick Commented Sep 19, 2013 at 12:11
  • Given the result, do you mean 'remove every key in the second array that is not in the first array'? – Rory McCrossan Commented Sep 19, 2013 at 12:12
  • And that first 'array' is an object with arrays as property values, not an array. – Andy Commented Sep 19, 2013 at 12:13
  • @Jahnux73 I seek through SO before asking, but didn't found that, thank you! – z-x Commented Sep 19, 2013 at 13:27
Add a ment  | 

2 Answers 2

Reset to default 4

The fastest way is to create a new object and only copy the keys you need.

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

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);
发布评论

评论列表(0)

  1. 暂无评论