Reputation: 4643
this is my object:
a={"a":"1","b":"2","c":"3","d":"4","e":"5","f":"6"}
This returns all the keys:
Object.keys(a)
["a", "b", "c", "d", "e", "f"]
This returns all the keys except 'a':
Object.keys(a).filter(function(k) {return k !== 'a'})
["b", "c", "d", "e", "f"]
how can I return all keys except 1 or more keys for example a
or b
or c
?
I have tried a few permutations but can't seem to get it, 1 below, or maybe it's not possible this way?
Object.keys(a).filter(function(k) {return k !== ('a','b')})
["a", "c", "d", "e", "f"]
Upvotes: 1
Views: 6129
Reputation: 51841
ES6 (ECMAScript 2015) you can use arrow functions:
Object.keys(a).filter(k => !~['a', 'b', 'c'].indexOf(k));
ES6 is not supported by all environments, so you can use ES5 alternative:
Object.keys(a).filter(function(k) {
return !~['a', 'b', 'c'].indexOf(k);
});
Upvotes: 2
Reputation: 4778
Object.keys(a).filter(function(k) {
return ["a", "b"].indexOf(k) === -1;
});
Just add the keys you want in the matched Array (one used with indexOf)
If you want something more portable:
function excludeKeys(obj, keys) {
return Object.keys(obj).filter(function(k) {
return keys.indexOf(k) === -1;
});
}
This way you can add any amount of excluded keys.
Upvotes: 2
Reputation: 8926
var a = ["a", "b", "c", "d", "e", "f"]
var b = a.filter(function(k) {return ['a','b'].indexOf(k) < 0})
// b => [ 'c', 'd', 'e', 'f' ]
Upvotes: 0