admin管理员组文章数量:1434407
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"]
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"]
Share
Improve this question
asked Feb 23, 2016 at 21:08
HattrickNZHattrickNZ
4,66315 gold badges61 silver badges103 bronze badges
2
-
1
k !== 'a' && k !== 'b'
? – Bergi Commented Feb 23, 2016 at 21:09 - @Bergi tks think yours is the simplist answer. – HattrickNZ Commented Feb 24, 2016 at 2:36
3 Answers
Reset to default 2Object.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.
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);
});
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' ]
本文标签: javascriptHow to return certain keys from an objectStack Overflow
版权声明:本文标题:javascript - How to return certain keys from an object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745624827a2666908.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论