Javascript 获取对象的键数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8763125/
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 array of object's keys
提问by Richard
I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.
我想以数组的形式获取 JavaScript 对象的键,无论是在 jQuery 还是纯 JavaScript 中。
Is there a less verbose way than this?
还有比这更简洁的方法吗?
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
回答by Raynos
Use Object.keys
:
使用Object.keys
:
var foo = {
'alpha': 'puffin',
'beta': 'beagle'
};
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
这是 ES5 的特性。这意味着它适用于所有现代浏览器,但不适用于旧版浏览器。
The ES5-shim has a implementation of Object.keys
you can steal
ES5-shim 有一个你可以窃取的实现Object.keys
回答by Rocket Hazmat
回答by alex
Of course, Object.keys()
is the bestway to get an Object's keys. If it's not available in your environment, it can be trivially shimmedusing code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()
's behaviour).
当然Object.keys()
是最好的获得一个对象的关键途径。如果它在您的环境中不可用,则可以使用例如您的示例中的代码对其进行微调(除非您需要考虑到您的循环将遍历原型链上的所有属性,这与Object.keys()
的行为不同)。
However, your example code...
但是,您的示例代码...
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
...could be modified. You can do the assignment right in the variablepart.
……可以修改。您可以直接在变量部分进行赋值。
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [], i = 0;
for (keys[i++] in foo) {}
Of course, this behaviour is different to what Object.keys()
actually does (jsFiddle). You could simply use the shim on the MDN documentation.
回答by Dexygen
I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)
我不知道不那么冗长,但我的灵感是通过单行请求将以下内容强制转换为一行,但不知道它是多么 Pythonic ;)
var keys = (function(o){var ks=[]; for(var k in o) ks.push(k); return ks})(foo);
回答by Cody Moniz
In case you're here looking for something to list the keys of an n-depth nested object as a flat array:
如果您在这里寻找将 n 深度嵌套对象的键列为平面数组的内容:
const getObjectKeys = (obj, prefix = '') => {
return Object.entries(obj).reduce((collector, [key, val]) => {
const newKeys = [ ...collector, prefix ? `${prefix}.${key}` : key ]
if (Object.prototype.toString.call(val) === '[object Object]') {
const newPrefix = prefix ? `${prefix}.${key}` : key
const otherKeys = getObjectKeys(val, newPrefix)
return [ ...newKeys, ...otherKeys ]
}
return newKeys
}, [])
}
console.log(getObjectKeys({a: 1, b: 2, c: { d: 3, e: { f: 4 }}}))
回答by Willem van der Veen
Summary
概括
For getting all of the keys of an Object you can use Object.keys()
. Object.keys()
takes an object as an argument and returns an array of all the keys.
要获取对象的所有键,您可以使用Object.keys()
. Object.keys()
将一个对象作为参数并返回一个包含所有键的数组。
Example:
例子:
const object = {
a: 'string1',
b: 42,
c: 34
};
const keys = Object.keys(object)
console.log(keys);
console.log(keys.length) // we can easily access the total amount of properties the object has
In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.
在上面的例子中,我们在键 const 中存储了一个键数组。然后我们可以通过检查键数组的长度轻松访问对象上的属性数量。
Getting the values with: Object.values()
获取值: Object.values()
The complementary function of Object.keys()
is Object.values()
. This function takes an object as an argument and returns an array of values. For example:
的互补函数Object.keys()
是Object.values()
。该函数将一个对象作为参数并返回一个值数组。例如:
const object = {
a: 'random',
b: 22,
c: true
};
console.log(Object.values(object));
回答by mohammad javad ahmadi
If you decide to use Underscore.js you better do
如果你决定使用 Underscore.js 你最好这样做
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
_.each( foo, function( val, key ) {
keys.push(key);
});
console.log(keys);