假设我这样创建一个对象:
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
检索属性名列表的最佳方法是什么?例如,我想以一些变量“键”结束,这样:
keys == ["ircEvent", "method", "regex"]
假设我这样创建一个对象:
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
检索属性名列表的最佳方法是什么?例如,我想以一些变量“键”结束,这样:
keys == ["ircEvent", "method", "regex"]
当前回答
注意Object。Firefox 4、Chrome 6、Safari 5、IE 9及以上版本均支持key和其他ECMAScript 5方法。
例如:
var o = {"foo": 1, "bar": 2};
alert(Object.keys(o));
ECMAScript 5兼容性表
新方法描述
其他回答
IE不支持(i in obj)原生属性。这是我能找到的所有道具的清单。
似乎stackoverflow做了一些愚蠢的过滤。
该列表可在这个谷歌组帖子的底部:- https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0
在支持js 1.8的浏览器下:
[i for(i in obj)]
正如slashnick指出的,您可以使用“for in”构造来遍历对象的属性名。但是,您将遍历对象原型链中的所有属性名。如果你只想遍历对象自己的属性,你可以使用object #hasOwnProperty()方法。因此有以下。
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
/* useful code here */
}
}
这里有很多答案…这是我的意见。
我需要一些东西来打印出所有的JSON属性,甚至是带有子对象或数组的属性(包括父名称)。
对于这个JSON:
mylittleJson = {
"one": "blah",
"two": {
"twoone": "",
"twotwo": "",
"twothree": ['blah', 'blah']
},
"three": ""
}
它会打印这个:
.one
.two.twoone
.two.twotwo
.two.twothree
.three
这是函数
function listatts(parent, currentJson){ var attList = [] if (typeof currentJson !== 'object' || currentJson == undefined || currentJson.length > 0) { return } for(var attributename in currentJson){ if (Object.prototype.hasOwnProperty.call(currentJson, attributename)) { childAtts = listatts(parent + "." + attributename, currentJson[attributename]) if (childAtts != undefined && childAtts.length > 0) attList = [...attList, ...childAtts] else attList.push(parent + "." + attributename) } } return attList } mylittleJson = { "one": "blah", "two": { "twoone": "", "twotwo": "", "twothree": ['blah', 'blah'] }, "three": "" } console.log(listatts("", mylittleJson));
希望这也能有所帮助。
因为我几乎在每个项目中都使用了underscore.js,所以我会使用keys函数:
var obj = {name: 'gach', hello: 'world'};
console.log(_.keys(obj));
它的输出将是:
['name', 'hello']