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

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

I'm pulling in JSON data from an external data source and part of the payload is an array that needs to be displayed as a series of key/value pairs.

I realize one way would be to transform the array into an interface/object via Typescript but in my case the data needs to be transformed declaratively in the Angular template's html markup.

So, given some data in the form of: heroes = ['Hurricane', 12, 'Wolf', 42, 'Zephyr', 28]

Displaying the data via *ngFor:

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

would render:

Hurricane
12
Wolf
42
Zephyr
28

However, what I need to display is:

Hurricane - 12
Wolf - 42
Zephyr - 28

Is there a way to do this declaratively inside the Angular 2 template file?

See Plunkr here

回答1:

You could transform the array you received using Array Extras into objects that better fit your view.

['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:

you can change heroes = [{name:'Hurricane', age:12}, {name:'Wolf', age:42}, {name:'Zephyr', age:28}]

Display the data <div *ngFor="let hero of heroes"> {{hero.name}} - {{hero.age}} </div>



回答3:

I created a function inside the component using cboston's code:

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; } 

Then, the Angular 2 client side markup looks like this:

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

Plunk available here: http://plnkr.co/edit/YnIL5drfWzIL5gMc1Efd?p=info



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!