如何遍历Angular 2中的对象属性

2022-01-24 00:00:00 loops iteration javascript angular ngfor

这是我的对象(它有 n 个动态键.我在下面的示例中只显示了两个)

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?

推荐答案

你可以这样做:

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

其中 generateArray 看起来像:

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

相关文章