2013-03-05 176 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]); 
    } 
}