在HTML5中显示嵌套的不等长JSON数组

时间:2014-09-15 19:21:43

标签: javascript json html5 angularjs

我有不同长度元素的嵌套数组的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或者它可以有另一个嵌套的数组,嵌套数组又会有另一个嵌套数组。

我想将所有数组元素显示在一个列表中,父列表元素具有子列表元素的链接,直到找不到子元素。

有人可以发布如何执行此任务的步骤吗?因为我能够找到等长数组的例子,但是没有找到这个嵌套情况的例子。

2 个答案:

答案 0 :(得分:1)

我认为这需要被认为是递归函数。 Recursion (JavaScript)

每次通过该方法,它会检查下一个级别是否为空,如果它不是"它是递归的"自称,通过下一级。

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);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

example

<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>
相关问题