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
2 Answers
Reset to default 4The 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
评论列表(0条)