1

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! :)

z-x
  • 411
  • 1
  • 6
  • 14

2 Answers2

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);
Tibos
  • 27,507
  • 4
  • 50
  • 64
3

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);
user2399923
  • 116
  • 2