如何显示嵌套结构的名称?

时间:2017-06-20 17:53:41

标签: javascript json

我有以下数据并尝试了以下操作,但我无法以names格式或以sub_values格式获取Test1, Test5, Test10, Test20, Test50的{​​{1}}(例如:[object Object]json格式且无法显示其length(即5,表示我们sub_values names为5,因此其长度为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 个答案:

答案 0 :(得分: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!

如何迭代你问的数组?现在这是完全不同的问题我的朋友!