获取 javascript 对象的第一个键名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3298477/
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
Get the first key name of a javascript object
提问by Anton Koval'
Let's assume we have the following javascript object:
假设我们有以下 javascript 对象:
ahash = {"one": [1,2,3], "two": [4,5,6]}
Exists any function, which returns the first key name in the object?
存在任何函数,它返回对象中的第一个键名?
From the example I want to get "one".
从这个例子中我想得到“一个”。
回答by Pickels
In Javascript you can do the following:
在 Javascript 中,您可以执行以下操作:
Object.keys(ahash)[0];
回答by Ned Batchelder
There's no such thing as the "first" key in a hash (Javascript calls them objects). They are fundamentally unordered. Do you mean just choose any single key:
没有哈希中的“第一个”键(Javascript 称它们为对象)。它们基本上是无序的。你的意思是只选择任何一个键:
for (var k in ahash) {
break
}
// k is a key in ahash.
回答by Bunyk
If you decide to use Underscore.js you better do
如果你决定使用 Underscore.js 你最好这样做
_.values(ahash)[0]
to get value, or
获得价值,或
_.keys(ahash)[0]
to get key.
拿到钥匙。
回答by nickf
Try this:
尝试这个:
for (var firstKey in ahash) break;
alert(firstKey); // 'one'
回答by Ilya Degtyarenko
You can query the content of an object, per its array position.
For instance:
您可以根据对象的数组位置查询对象的内容。
例如:
let obj = {plainKey: 'plain value'};
let firstKey = Object.keys(obj)[0]; // "plainKey"
let firstValue = Object.values(obj)[0]; // "plain value"
/* or */
let [key, value] = Object.entries(obj)[0]; // ["plainKey", "plain value"]
console.log(key); // "plainKey"
console.log(value); // "plain value"
回答by mjlescano
With Underscore.js, you could do
使用 Underscore.js,你可以做到
_.find( {"one": [1,2,3], "two": [4,5,6]} )
It will return [1,2,3]
它将返回 [1,2,3]
回答by random_user_name
I use Lodashfor defensive codingreasons.
我出于防御性编码的原因使用Lodash。
In particular, there are cases where I do not know if there will or will not be any properties in the object I'm trying to get the key for.
特别是,在某些情况下,我不知道我正在尝试获取其密钥的对象中是否有任何属性。
A "fully defensive" approach with Lodashwould use both keysas well as get:
const firstKey = _.get(_.keys(ahash), 0);
回答by yilmazhuseyin
you can put your elements into an array and hash at the same time.
您可以将元素放入数组并同时进行散列。
var value = [1,2,3];
ahash = {"one": value};
array.push(value);
array can be used to get values by their order and hash could be used to get values by their key. just be be carryfull when you remove and add elements.
数组可用于按顺序获取值,散列可用于按键获取值。当您删除和添加元素时,请随身携带。

