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

Angular 2: How would you display an array as a series of Key/Value pairs?

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

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

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

通过 *ngFor 显示数据:

 <div *ngFor="let hero of heroes">
 {{hero}}
 </div>

将呈现:

飓风
12

42
和风
28

但是,我需要显示的是:

飓风 - 12
狼 - 42
西风号 - 28

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

Plunkr here

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

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

您可以使用 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/

我使用 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;
}

然后,Angular2 客户端标记如下所示:

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

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