How to iterate through an Object attributes in Angular 2
Asked Answered
C

3

31

Here's my object (It has n number of dynamic keys. I've only shown two in the example below)

let obj = {
abc:["some text", "some more text"],
xyz:["more text", "what do you think?", "I'm tired now"]

}

Here's my attempt to loop throw the above and print all the values

 <div *ngFor='let item of obj ; let i = index;'>
            <p *ngFor="let value of obj.i">{{value}}
 </div>

But the above doesn't appear to work. What am I doing wrong and what's the correct syntax?

Celibacy answered 20/8, 2016 at 23:21 Comment(1)
Did you try obj[i] instead of obj.i?Niobic
H
44

You could do something like this:

<li *ngFor="let o of obj">
   <p *ngFor="let objArrayElement of generateArray(o)"> {{objArrayElement}} </p>
</li>

where generateArray looks like:

generateArray(obj){
   return Object.keys(obj).map((key)=>{ return obj[key]});
}
Harald answered 20/8, 2016 at 23:25 Comment(2)
@Aarmora nice to know that it was helpful for you. :)Harald
but let o of obj in angular2 is not allowed, because obj is not iterateble, correct?Longbow
B
26

slight modification to @eg16's answer and it worked like a charm for me -

the generateArray function looks like this-

generateArray(obj){
    return Object.keys(obj).map((key)=>{ return {key:key, value:obj[key]}});
}

and the template -

<li *ngFor="let item of generateArray(data)">{{item.key}}: {{item.value}}</li>
Bette answered 5/5, 2017 at 10:48 Comment(0)
R
21

Starting with version 6.1, a KeyValue Pipe is made available by Angular:

<li *ngFor="let item of (data | keyvalue)">{{item.key}}: {{item.value}}</li>

This makes previous workarounds using Object.keys references or own implementations thereof obsolete.

Rosecan answered 11/4, 2019 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.