javascript 获取JS中单键未知的对象的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32208902/
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-10-28 14:58:27  来源:igfitidea点击:

Get the value of an object with an unknown single key in JS

javascriptjavascript-objects

提问by Osama

How can I get the value of an object with an unknown single key?

如何获取具有未知单键的对象的值?

Example:

例子:

var obj = {dbm: -45}

I want to get the -45 value without knowing its key.

我想在不知道其键的情况下获得 -45 值。

I know that I can loop over the object keys (which is always one).

我知道我可以遍历对象键(总是一个)。

for (var key in objects) {
    var value = objects[key];
}

But I would like to know if there is a cleaner solution for this?

但我想知道是否有更清洁的解决方案?

回答by Blauharley

Object.keys might be a solution:

Object.keys 可能是一个解决方案:

Object.keys({ dbm: -45}); // ["dbm"]

The differences between for-in and Object.keys is that Object.keys returns all own key names and for-in can be used to iterate over all own and inherited key names of an object.

for-in 和 Object.keys 的区别在于 Object.keys 返回所有自己的键名,而 for-in 可用于迭代对象的所有自有和继承的键名。

As James Brierley commented below you can assign an unknown property of an object in this fashion:

正如 James Brierley 在下面评论的那样,您可以以这种方式分配对象的未知属性:

var obj = { dbm:-45 };
var unkownKey = Object.keys(obj)[0];
obj[unkownKey] = 52;

But you have to keep in mind that assigning a property that Object.keys returns key name in some order of might be error-prone.

但是您必须记住,分配 Object.keys 以某种顺序返回键名的属性可能容易出错。

回答by T.J. Crowder

There's a new option now: Object.values. So if you knowthe object will have just one property:

现在有一个新选项:Object.values. 因此,如果您知道该对象将只有一个属性:

const array = Object.values(obj)[0];

Live Example:

现场示例:

const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const array = Object.values(obj)[0];
console.log(array);

If you need to know the name of the property as well, there's Object.entriesand destructuring:

如果您还需要知道属性的名称,则有Object.entries和解构:

const [name, array] = Object.entries(obj)[0];

Live Example:

现场示例:

const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const [name, array] = Object.entries(obj)[0];
console.log(name);
console.log(array);