我有如下所示的具有不等长度元素的嵌套数组JSON字符串,我希望使用Javascript或Angular.js在页面中显示它。
{ [
'id':1,
'value':'tes1'
'nextLevel':['id':12,
'value':'tes12'
'nextLevel':['id':13,
'value':'tes13',
nextLevel:null ],
]
],
['id':2,
'value':'tes2'
'nextLevel':null ]
]在这里,nextLevel可以是null,或者它可以有另一个嵌套的数组,嵌套数组反过来又会有另一个嵌套数组。
我想将所有数组元素显示到一个列表中,而父列表元素有到子列表元素的链接,直到没有找到子元素为止。
有人能张贴有关如何执行此任务的步骤吗?因为我能够找到等长数组的示例,但是对于这个嵌套的情况,找不到任何示例。
发布于 2014-09-15 19:42:57
我认为这需要被认为是递归函数。递归(JavaScript)
每次通过该方法,它都会检查下一个级别是否为null,如果不是,则“递归”调用自己,从而传递下一个级别。
http://jsfiddle.net/k8Lratja/
var ary = {
'id': 1,
'value': 'tes1',
'nextLevel': {
'id': 12,
'value': 'tes12',
'nextLevel': {
'id': 13,
'value': 'tes13',
'nextLevel': null
}
}
};
function objectDisplay(objectIn) {
document.write(objectIn.id + ' ' + objectIn.value + "<br />");
if (objectIn.nextLevel !== null) {
objectDisplay(objectIn.nextLevel);
}
}
objectDisplay(ary);
发布于 2014-09-15 20:24:29
角示例
<div class="ctrl" ng-app="app" ng-controller="ctrl" >
<div ng-repeat="idLevel in data">
<div>
{{idLevel.id}} = {{idLevel.value}}
<div ng-repeat="nextLevel1 in idLevel.nextLevel" style="margin-left: 20px;">
{{nextLevel1.id}}={{nextLevel1.value}}
<div ng-repeat="nextLevel2 in nextLevel1.nextLevel" style="margin-left: 20px;">
{{nextLevel2.id}}={{nextLevel2.value}}
<div ng-repeat="nextLevel3Item in nextLevel2.nextLevel" style="margin-left: 20px;">
{{nextLevel3Item.id}}={{nextLevel3Item.value}}
</div>
</div>
</div>
</div>
</div>
</div>https://stackoverflow.com/questions/25855384
复制相似问题