1

I would like to be able to get and list the keys (not values) from the params array in this JSON Object, using the *ngfor directive in an ionic2 page.

{
 "id":"x",
 "name":"xxx",
 "code":"xxx",
 "description":"xxx",
 "params":
         [
          {"param1": "params1"},
          {"param2": "params2"},
          {"param3": "params3"}
         ]
}

I have searched around this forum and found an implementation using pipes; but I have been unsuccessful so far. The most I've been able to obtain using the pipes are the array indexes, but not the keys.

onyekam
  • 13
  • 8

1 Answers1

1
import { PipeTransform , Pipe } from '@angular/core';
@Pipe( { name : 'keys' } )
export class KeysPipe implements PipeTransform {
    transform ( value , args : string[] ) : any {
        let keys = [];
        for ( let key in value ) {
            if ( value.hasOwnProperty( key ) ) {
                keys.push( key );
            }
        }
        return keys;
    }
}

And use it like this :

                       <ul>
                          <li *ngFor="let item of obj.params  ">
                           <span  *ngFor="let key of item | keys  ">{{key  }}</span>
                          </li>
                        </ul> 

Here is the plunker

Note that plunker is using # , you should use let instead , like above.

Milad
  • 27,506
  • 11
  • 76
  • 85