获取键/值 javascript 对象的键的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6268679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:02:25  来源:igfitidea点击:

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

javascriptjquery

提问by sprugman

If I have a JS object like:

如果我有一个 JS 对象,例如:

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

If I know that foohas 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....

如果我知道它foo具有基本的键/值结构,但不知道键的名称,那么获取它的最简单方法是什么?for ... in? $.each()? 我希望有更好的东西......

采纳答案by Felix Kling

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

如果您想获取所有密钥,ECMAScript 5 引入了Object.keys. 这仅受较新的浏览器支持,但MDC 文档提供了另一种实现(也使用for...inbtw):

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...inis the only reasonable solution.

当然,如果您同时想要键和值,那么这for...in是唯一合理的解决方案。

回答by Michael Benin

You would iterate inside the object with a for loop:

您将使用 for 循环在对象内部进行迭代:

for(var i in foo){
  alert(i); // alerts key
  alert(foo[i]); //alerts key's value
}

Or

或者

Object.keys(foo)
  .forEach(function eachKey(key) { 
    alert(key); // alerts key 
    alert(foo[key]); // alerts value
  });

回答by user01

You can access each key individually without iterating as in:

您可以单独访问每个键而无需迭代,如下所示:

var obj = { first: 'someVal', second: 'otherVal' };
alert(Object.keys(obj)[0]); // returns first
alert(Object.keys(obj)[1]); // returns second

回答by Aryeh Beitz

Given your Object:

鉴于您的对象:

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

To get bar, use:

要获得bar,请使用:

Object.keys(foo)[0]

To get baz, use:

要获得baz,请使用:

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

Assuming a single object

假设单个对象

回答by theonelucas

A one linerfor 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

回答by Mustkeem K

This is the simplest and easy way. This is how we do this.

这是最简单和容易的方法。这就是我们这样做的方式。

var obj = { 'bar' : 'baz' }
var key = Object.keys(obj)[0];
var value = obj[key];
     
 console.log("key = ", key) // bar
 console.log("value = ", value) // baz
Object.keys() 是 javascript 方法,它在对象上使用时返回一个键数组。

Object.keys(obj) // ['bar']

Now you can iterate on the objects and can access values like below-

现在您可以迭代对象并可以访问如下值 -

Object.keys(obj).forEach( function(key) {
  console.log(obj[key]) // baz
})

回答by Chris

I was having the same problem and this is what worked

我遇到了同样的问题,这是有效的

//example of an Object
var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
};

//How to access a single key or value
var key = Object.keys(person)[0];
var value = person.firstName;

回答by aiffin

// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}

Refer MDN

参考 MDN

回答by patapizza

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

除了 ,我什么都看不到for (var key in foo)

回答by Jamie Treworgy

There is no way other than for ... in. If you don't want to use that (parhaps because it's marginally inefficient to have to test hasOwnPropertyon each iteration?) then use a different construct, e.g. an array of kvp's:

除了 没有别的办法for ... in。如果您不想使用它(可能是因为hasOwnProperty每次迭代都必须进行测试效率很低?)然后使用不同的构造,例如 kvp 数组:

[{ key: 'key', value: 'value'}, ...]