假设我这样创建一个对象:
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
检索属性名列表的最佳方法是什么?例如,我想以一些变量“键”结束,这样:
keys == ["ircEvent", "method", "regex"]
假设我这样创建一个对象:
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
检索属性名列表的最佳方法是什么?例如,我想以一些变量“键”结束,这样:
keys == ["ircEvent", "method", "regex"]
当前回答
这可以在大多数浏览器中工作,甚至在IE8中,并且不需要任何类型的库。Var I是你的钥匙。
var myJSONObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
var keys=[];
for (var i in myJSONObject ) { keys.push(i); }
alert(keys);
其他回答
在支持js 1.8的浏览器下:
[i for(i in obj)]
解决方案工作在我的情况和跨浏览器:
var getKeys = function(obj) {
var type = typeof obj;
var isObjectType = type === 'function' || type === 'object' || !!obj;
// 1
if(isObjectType) {
return Object.keys(obj);
}
// 2
var keys = [];
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
keys.push(i)
}
}
if(keys.length) {
return keys;
}
// 3 - bug for ie9 <
var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');
if(hasEnumbug) {
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
var nonEnumIdx = nonEnumerableProps.length;
while (nonEnumIdx--) {
var prop = nonEnumerableProps[nonEnumIdx];
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
keys.push(prop);
}
}
}
return keys;
};
使用Reflect.ownKeys ()
var obj = {a: 1, b: 2, c: 3};
Reflect.ownKeys(obj) // ["a", "b", "c"]
对象。键和对象。getOwnPropertyNames不能获得不可枚举的属性。它甚至适用于不可枚举的属性。
var obj = {a: 1, b: 2, c: 3};
obj[Symbol()] = 4;
Reflect.ownKeys(obj) // ["a", "b", "c", Symbol()]
如果你只是想获取元素,而不是函数,那么这段代码可以帮助你
this.getKeys = function() {
var keys = new Array();
for(var key in this) {
if( typeof this[key] !== 'function') {
keys.push(key);
}
}
return keys;
}
这是我的HashMap实现的一部分,我只想要键,“this”是包含键的HashMap对象
正如slashnick指出的,您可以使用“for in”构造来遍历对象的属性名。但是,您将遍历对象原型链中的所有属性名。如果你只想遍历对象自己的属性,你可以使用object #hasOwnProperty()方法。因此有以下。
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
/* useful code here */
}
}