Reputation: 451
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! :)
Upvotes: 1
Views: 3564
Reputation: 126
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);
Upvotes: 3
Reputation: 27823
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);
Upvotes: 4