最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to return certain keys from an object - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 2
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.

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' ]
发布评论

评论列表(0)

  1. 暂无评论