jQueryJavaScript: Filter array with another array - Stack Overflow

Let's say I have two arrays:{First: [One, Two, Three], Second: [One, Two, Three], Third: [One, Two

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745146385a4613667.html

相关推荐

  • jQueryJavaScript: Filter array with another array - Stack Overflow

    Let's say I have two arrays:{First: [One, Two, Three], Second: [One, Two, Three], Third: [One, Two

    1小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信