我有以下數據,並試圖下面,但我無法得到names
sub_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。
您需要遍歷jsondata才能獲取所需的值。現在你正在訪問一個不存在的數組的屬性。 – Shadowfool
看看這個遍歷數組中的對象等: https://jsfiddle.net/w2c3fgvh/1/ – Woodrow
@Woodrow,這很好,謝謝你的幫助。 – Guna