Get all keys of a JavaScript object
I was wondering if there was a quick way to extract keys of associative array into an array, or comma-separated list using JavaScript (jQuery is ok).
options = {key1: "value1", key2: "value2"};
Result should be the array:
["key1", "key2"]
or just a string:
"key1, key2"
You can easily get an array of them via a for
loop, for example:
var keys = [];
for(var key in options) {
if(options.hasOwnProperty(key)) { //to be safe
keys.push(key);
}
}
Then use keys
how you want, for example:
var keyString = keys.join(", ");
You can test it out here. The .hasOwnProperty()
check is to be safe, in case anyone messed with the object prototype and such.
options = {key1: "value1", key2: "value2"};
keys = Object.keys(options);
一个jQuery的方式:
var keys = [];
options = {key1: "value1", key2: "value2"};
$.each(options, function(key, value) { keys.push(key) })
console.log(keys)
链接地址: http://www.djcxy.com/p/27370.html
上一篇: 如何列出javascript对象的函数/方法? (它甚至有可能吗?)
下一篇: 获取JavaScript对象的所有键