2013-03-05 173 views
0

我有这个数组Json,我怎么能得到对象的名字? 这是我的阵列json:获取对象的名称

var datos = {"animales":[ 
{ 
    "nombre":"Lucy", 
    "animal":"Cat", 
    "breed":"American Shorthair", 
    "note":"She raised me" 
}, 
{ 
    "nombre":"Homer", 
    "animal":"Cat", 
    "breed":"unknown", 
    "note":"Named after a world-famous bassoonist" 
}, 
{ 
    "nombre":"Muchacha", 
    "animal":"Dog", 
     "breed":"mutt", 
     "note":"One of the ugliest dogs I’ve ever met" 
    } 
]} 

我怎么能得到密钥的名称? (农布雷,动物,品种,注意) 我尝试这种方式,但它不工作:

for (key in datos) { 
       HtmlT += "<td>" + datos.animales[key]+ "</td>"; // it should return nombre 
      } 

datos.animales [关键]返回undefind

+0

这不是JSON,这是一个JavaScript对象初始化。 2013-03-05 12:49:18

回答

1

你所列出的名称AREN属性datos,它们是animales数组中条目的属性。因此,您必须循环访问animales阵列,并且对于每个条目,请使用for-in来遍历该条目的属性名称。

var animales, index, entry; 

animales = datos.animales; 
for (index = 0; index < animales.length; ++index) { 
    entry = animales[index]; 
    for (key in entry) { 
     // Here, `key` will have the names `"nombre"`, `"animal"`, etc. 
    } 
} 

或者在支持ES5的环境,或者如果您使用的是ES5垫片:

dataos.animales.forEach(function(entry) { 
    var key; 

    for (key in entry) { 
     // Here, `key` will have the names `"nombre"`, `"animal"`, etc. 
    } 
}); 

注意,属性名可能不适合所有条目相同的(尽管当然,他们可能是如果这就是你的数据定义的方式)。

-1

尝试

for (key in datos) { 
    for (animal in datos[key]) { 
    HtmlT+= "\"" + animal + "\""; 
    } 
} 

做的,每种类型的循环,当key是实际的密钥和object[key]将返回值。

+0

[请勿在没有安全措施的阵列上使用'for-in'](http://blog.niftysnippets.org/2010/11/myths-and-realities-of-forin.html) – 2013-03-05 12:52:29

0

试试这个:

for (key in datos.animales[0]) { HtmlT += "" + datos.animales[0][key]+ ""; } 

这是你正在寻找的实际元素。

你可能要循环的DATOS阵列

0

你可以试试:

for(var index in datos.animales){ 
    var animal = datos.animales[i]; 
    for(var prop in animal){ 
     console.log(prop+":"+animal[prop]); 
    } 
}