Iterate over object in Angular

前端 未结 17 1555
攒了一身酷
攒了一身酷 2020-11-22 12:19

I am trying to do some things in Angular 2 Alpha 28, and am having an issue with dictionaries and NgFor.

I have an interface in TypeScript looking like this:

17条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 12:41

    Adding to SimonHawesome's excellent answer. I've made an succinct version which utilizes some of the new typescript features. I realize that SimonHawesome's version is intentionally verbose as to explain the underlying details. I've also added an early-out check so that the pipe works for falsy values. E.g., if the map is null.

    Note that using a iterator transform (as done here) can be more efficient since we do not need to allocate memory for a temporary array (as done in some of the other answers).

    import {Pipe, PipeTransform} from '@angular/core';
    
    @Pipe({
        name: 'mapToIterable'
    })
    export class MapToIterable implements PipeTransform {
        transform(map: { [key: string]: any }, ...parameters: any[]) {
            if (!map)
                return undefined;
            return Object.keys(map)
                .map((key) => ({ 'key': key, 'value': map[key] }));
        }
    }
    

提交回复
热议问题