文章内容

2020/6/23 14:15:18,作 者: 黄兵

Angular json遍历

最近再使用Angular的时候,后端返回了一个复杂的数组,具体内容如下:

        var temp_array = [{
            'parent': {
                'child': {'link': '/help/why_some_numbers_disappear', 'title': 'Why some numbers disappear'},
                'title': 'Phone Number'
            }
        },
        {
            'parent': {
                'child': {
                    'link': '/help/why_some_numbers_disappear',
                    'title': 'Why sometimes website access is slow'
                    }, 
                'title': 'WebSite'
            }
        }]

这个数组解析第一层没有问题,具体代码如下:

<article class="page no-article-survey content-width">
<mat-accordion>
<mat-expansion-panel *ngFor="let item of result">
<mat-expansion-panel-header>
<mat-panel-title>
{{item.parent.title}}
</mat-panel-title>
</mat-expansion-panel-header>

<div class="overflow">
<div class="children">
<div class="child" *ngFor="let childItem of item.parent.child">
<a [routerLink]="[childItem.link]">{{childItem.title}}</a>
</div>
</div>
</div>
</mat-expansion-panel>
</mat-accordion>
</article>

但是子数据,会存在[object,object]的情况。导致无法解析:

具体循环代码如下:

        for(let item of temp_array){
            for(let childItem of item.parent.child){
                console.log(childItem);
            }
        }

最后修改代码,如下:

        //called with every property and its value
        function process(keyvalue) {
            console.log(key + " :" + value);
        }

        function traverse(ofunc) {
            for (var i in o) {
                func.apply(this, [io[i]]);
                if (o[i] !== null && typeof (o[i]) == "object") {
                    //going one step down in the object tree!!
                    traverse(o[i], func);
                }
            }
        }

        //that's all... no magic, no bloated framework
        traverse(temp_arrayprocess);

运行结果:


但是再Angular 还是不好操作,只能修改后端代码,将child节点变成一个数组,具体数据如下:

        var temp_array = [{'parent': {
                'child': [{'link': '/help/why_some_numbers_disappear', 'title': 'Why some numbers disappear'}],
                'title': 'Phone Number'}
                }, {'parent': {
                'child': [{'link': '/help/why_some_numbers_disappear', 'title': 'Why sometimes website access is slow'}],
                'title': 'WebSite'}
                }]

之后就可以循环遍历了。

代码如下:

<article class="page no-article-survey content-width">
<mat-accordion>
<mat-expansion-panel *ngFor="let item of result">
<mat-expansion-panel-header>
<mat-panel-title>
{{item.parent.title}}
</mat-panel-title>
</mat-expansion-panel-header>

<div class="overflow">
<div class="children">
<div class="child" *ngFor="let childItem of item.parent.child">
<a [routerLink]="[childItem.link]">{{childItem.title}}</a>
</div>
</div>
</div>
</mat-expansion-panel>
</mat-accordion>
</article>


参考资料:

1、使用JavaScript遍历JSON对象树的所有节点

分享到:

发表评论

评论列表