best way to get the key of a key/value javascript

2019-01-02 17:27发布

If I have a JS object like:

var foo = { 'bar' : 'baz' }

If I know that foo has that basic key/value structure, but don't know the name of the key, what's the easiest way to get it? for ... in? $.each()? I hope there's something better....

16条回答
看风景的人
2楼-- · 2019-01-02 18:02

Since you mentioned $.each(), here's a handy approach that would work in jQuery 1.6+:

var foo = { key1: 'bar', key2: 'baz' };

// keys will be: ['key1', 'key2']
var keys = $.map(foo, function(item, key) {
  return key;
});
查看更多
伤终究还是伤i
3楼-- · 2019-01-02 18:02

Well $.each is a library construct, whereas for ... in is native js, which should be better

查看更多
只靠听说
4楼-- · 2019-01-02 18:04

If you want to get all keys, ECMAScript 5 introduced Object.keys. This is only supported by newer browsers but the MDC documentation provides an alternative implementation (which also uses for...in btw):

if(!Object.keys) Object.keys = function(o){
     if (o !== Object(o))
          throw new TypeError('Object.keys called on non-object');
     var ret=[],p;
     for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
     return ret;
}

Of course if you want both, key and value, then for...in is the only reasonable solution.

查看更多
墨雨无痕
5楼-- · 2019-01-02 18:04

I don't see anything else than for (var key in foo).

查看更多
ら面具成の殇う
6楼-- · 2019-01-02 18:07

Given your Object:

var foo = { 'bar' : 'baz' }

To get bar, use:

Object.keys(foo)[0]

To get baz, use:

foo[Object.keys(foo)[0]]

Assuming a single object

查看更多
千与千寻千般痛.
7楼-- · 2019-01-02 18:09

A one liner for you:

const OBJECT = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
    'key4': 'value4'
};

const value = 'value2';

const key = Object.keys(OBJECT)[Object.values(OBJECT).indexOf(value)];

window.console.log(key); // = key2
查看更多
登录 后发表回答