Angular 2:如何将数组显示为一系列键/值对?

时间:2016-09-15 21:21:35

标签: angular ngfor

我从外部数据源提取JSON数据,部分有效负载是需要显示为一系列键/值对的数组。

我意识到一种方法是通过Typescript将数组转换为接口/对象,但在我的情况下,需要在Angular模板的html标记中以声明方式转换数据。

因此,给出一些以下形式的数据: heroes = ['Hurricane', 12, 'Wolf', 42, 'Zephyr', 28]

通过* ngFor:

显示数据
 <div *ngFor="let hero of heroes">
 {{hero}}
 </div>

会呈现:

飓风
12个
沃尔夫
42个
西风
28个

但是,我需要显示的是:

飓风 - 12
狼 - 42
Zephyr - 28

有没有办法在Angular 2模板文件中以声明方式执行此操作?

请参阅Plunkr here

3 个答案:

答案 0 :(得分:3)

您可以更改heroes = [{name:'Hurricane', age:12}, {name:'Wolf', age:42}, {name:'Zephyr', age:28}]

显示数据<div *ngFor="let hero of heroes"> {{hero.name}} - {{hero.age}} </div>

答案 1 :(得分:2)

您可以将使用Array Extras收到的数组转换为更适合您视图的对象。

['Hurricane', 12, 'Wolf', 42, 'Zephyr', 28]
    .map(function(curr, index, arr) { 
        if(typeof curr === 'number') 
            return {name: arr[index-1], id: curr } 
        })
    .filter(function(val) { return val })

https://blogs.msdn.microsoft.com/ie/2010/12/13/ecmascript-5-part-2-array-extras/

答案 2 :(得分:0)

我使用cboston的代码在组件内部创建了一个函数:

mapArray(args){
   var results = args.map(function (current, index, arr) {
        if(typeof current == 'number'){
            return {
                name: arr[index - 1],
                age: current
            }
        }
    }).filter(function(val) {
        return val;
    });

    return results;
}

然后,Angular 2客户端标记看起来像这样:

<div *ngFor="let hero of mapArray(heroes)">
  {{hero.name}} : {{hero.age}}
 </div>

此处提供插件:http://plnkr.co/edit/YnIL5drfWzIL5gMc1Efd?p=info