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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39059552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:09:42  来源:igfitidea点击:

How to iterate through an Object attributes in Angular 2

javascriptloopsangulariterationngfor

提问by user6123723

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

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

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?

但以上似乎不起作用。我做错了什么,正确的语法是什么?

回答by etrupja

You could do something like this:

你可以这样做:

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

where generateArraylooks like:

其中generateArray的样子:

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

回答by Avinash

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

对@eg16 的回答稍作修改,它对我来说就像一个魅力 -

the generateArray function looks like this-

generateArray 函数看起来像这样 -

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>

回答by Jens Habegger

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

从 6.1 版开始,Angular 提供了一个KeyValue 管道

<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.

这使得以前使用 Object.keys 引用或其自己的实现的变通方法已过时。