2017-06-20 23 views
-2

我有以下數據,並試圖下面,但我無法得到namessub_values的(如:Test1, Test5, Test10, Test20, Test50)無論是在[object Object]格式或json格式,無法顯示其length或者(即5,意味着我們有sub_values names是五個,所以它的長度是5)。如何顯示嵌套結構的名稱?

var jsondata = [ 
{"id": "1","name": "test1","sub_values": [{"id": "1","name": "Test1","sub_values": []}]}, 
{"id": "2","name": "test2","sub_values": [{"id": "1","name": "Test5","sub_values": []},{"id": "1","name": "Test10","sub_values": []},{ "id": "1","name": "Test20","sub_values": []}]}, 
{"id": "3","name": "test3","sub_values": [{"id": "1","name": "Test50","sub_values": []}]} 
]; 

console.log(jsondata);//(3) [Object, Object, Object] 
console.log(jsondata.sub_values.name);//Cannot read property 'name' of undefined 
console.log(jsondata.sub_values.length);//Cannot read property 'length' of undefined 

錯誤:Cannot read property 'name' of undefined

Cannot read property 'length' of undefined 

請讓我知道如何得到這一點。

創建Fiddle

+1

您需要遍歷jsondata才能獲取所需的值。現在你正在訪問一個不存在的數組的屬性。 – Shadowfool

+1

看看這個遍歷數組中的對象等: https://jsfiddle.net/w2c3fgvh/1/ – Woodrow

+0

@Woodrow,這很好,謝謝你的幫助。 – Guna

回答

2

由於您的jsondata是一個數組(或更好地指向一個數組),您還應該提及相同的索引。那麼,爲什麼你不試試這個,讓我知道如果這工作或沒有。請參閱下面的代碼註釋。

console.log(jsondata[0]);//(3) Try this first 
console.log(jsondata[0].sub_values[0].name);// Oh! You are onto something here. 
console.log(jsondata[0].sub_values[0].length);// Now you realized you need to iterate an array! 

如何迭代你問的數組?現在,這是完全不同的問題我的朋友!

-1

jsondata是一個數組。要訪問您還需要添加索引。

console.log(jsondata[0].sub_values[0].id) 
console.log(jsondata[0].sub_values[0].name)