1

我想以字符串形式获取 json 对象的参数名称

myObject = { "the name": "the value", "the other name": "the other value" } 

有没有办法得到"the name""the other name"结果?

4

4 回答 4

4

在 jQuery 中:

var myObject = { "the name": "the value", "the other name": "the other value" };
var indexes = [];
$.each(myObject,function(index,value){
   indexes.push(index);
});

console.log(indexes[0]) -> the name
console.log(indexes[1]) -> the other name

在纯js中:

var myObject = { "the name": "the value", "the other name": "the other value" };
var indexes = [];
for(var index in myObject){
    indexes.push(index);
}

console.log(indexes[0]) -> the name
console.log(indexes[1]) -> the other name

在上面你可以随时打破。如果您需要所有索引,有更快的方法将它们放入数组中:

var myObject = { "the name": "the value", "the other name": "the other value" };
var indexes = Object.keys(myObject);

console.log(indexes[0]) -> the name
console.log(indexes[1]) -> the other name
于 2013-10-26T23:07:13.927 回答
1

当然。您可以使用for-in循环来获取对象的属性名称。

for ( var prop in myObject ){
   console.log("Property name is: " + prop + " and value is " + myObject[prop]);
}

更多关于 for-in 的信息

于 2013-10-26T23:06:39.747 回答
1

我不确定您要完成什么,但是您可以使用 Object.keys(object) 轻松获取对象的键

Object.keys(myObject)

这会给你一个对象键的数组,你可以用它做任何你想做的事情。

于 2013-10-26T23:09:00.287 回答
1

大多数现代浏览器将允许您使用该Object.keys方法从 JSON 对象中获取键列表(这就是您要查找的字符串的名称)。所以,你可以简单地使用

var keys = Object.keys(myJsonObject);

获取键数组并根据需要使用这些键。

于 2013-10-26T23:12:57.723 回答