0

I have this set of data that i want to use in one of my ng2 projects:

{
  "Administration et gestion": [
    {
        "id": "1_1",
        "text": "Assistance comptable"
    },
    {
        "id": "1_2",
        "text": "Conseil fiscal et impots"
    },
    {
        "id": "1_3",
        "text": "Conseil juridique"
    },
    {
        "id": "1_4",
        "text": "Conseil auto-entrepreneur"
    }
  ],
  "Animaux": [
    {
        "id": "2_1",
        "text": "garde d'animaux"
    },
    {
        "id": "2_2",
        "text": "toitellage"
    }
  ],
  "Enfants": [
      {
          "id": "3_1",
          "text": "baby-sitting"
      },
      {
          "id": "3_2",
          "text": "aides au devoirs"
      }
  ],
}

Getting this data into ng1 was easy, I was doing something like this:

ng-repeat="(key, skill) in skills"

but angular2 doesn't support angular1 syntax, and solutions found don't work for me (some pipes). Rather that finding and pasting something randomly, can anyone help me to fully understand what I have to do here?

danday74
  • 52,471
  • 49
  • 232
  • 283
PrinceZee
  • 1,587
  • 3
  • 11
  • 24
  • Possible duplicate of [Iterate through json string in Observable angular js 2](http://stackoverflow.com/questions/35339411/iterate-through-json-string-in-observable-angular-js-2) – Günter Zöchbauer Mar 10 '16 at 09:40

1 Answers1

3

You could create a custom pipe for this:

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

And use it like that:

<div *ngFor="#keyValue of skills | keys">
  <div>{{keyValue.key}}<div>
  <div *ngFor="#value of keyValue.value">
    {{value.id}} = {{value.text}}
  </div>
</div>

Don't forget to add the pipe in the pipes attribute of your component:

@Component({
  (...)
  pipes: [ KeysPipe ]
})

See this question for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360