Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created April 13, 2016 23:26
Show Gist options
  • Save amcdnl/202596c5b85cc66d7002d10bde3ab514 to your computer and use it in GitHub Desktop.
Save amcdnl/202596c5b85cc66d7002d10bde3ab514 to your computer and use it in GitHub Desktop.
import { Pipe } from 'angular2/core.js';
/**
* Map to Iteratble Pipe
*
* It accepts Objects and [Maps](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
*
* Example:
*
* <div *ngFor="#keyValuePair of someObject | mapToIterable">
* key {{keyValuePair.key}} and value {{keyValuePair.value}}
* </div>
*
*/
@Pipe({ name: 'mapToIterable' })
export class MapToIterable {
transform(value) {
let result = [];
if(value.entries) {
for (var [key, value] of value.entries()) {
result.push({ key, value });
}
} else {
for(let key in value) {
result.push({ key, value: value[key] });
}
}
return result;
}
}
@ocombe
Copy link

ocombe commented Jul 8, 2016

Updated version for angular 2 rc4 that works in ES5:

import {Pipe, PipeTransform} from '@angular/core';

/**
 * Iterable Pipe
 *
 * It accepts Objects and [Maps](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
 *
 * Example:
 *
 *  <div *ngFor="let keyValuePair of someObject | iterable">
 *    key {{keyValuePair.key}} and value {{keyValuePair.value}}
 *  </div>
 *
 */
@Pipe({name: 'iterable'})
export class IterablePipe implements PipeTransform {
    transform(iterable: any, args: any[]): any {
        let result = [];

        if(iterable.entries) {
            iterable.forEach((key, value) => {
                result.push({key, value});
            });
        } else {
            for(let key in iterable) {
                if(iterable.hasOwnProperty(key)) {
                    result.push({key, value: iterable[key]});
                }
            }
        }

        return result;
    }
}

@jiayihu
Copy link

jiayihu commented May 31, 2017

The Pipe should be defined as impure with pure: false because iterables like Map doesn't change reference when using their methods. Be careful with large iterables though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment