我有一个 json 对象,我尝试将其转换为数组,否则当我循环它时,我得到 [object object],在我的代码中我尝试了一些可行的方法,但它只显示每个字段的值而不是显示键 => 值。
如何在我的 html 中显示我的 json 的键和值? 有没有更好的方法将对象转换为数组?
json
{
"toto": [
"titi",
"tata"
],
"foo": [
"foobar",
"footix"
]
}
ts.file
fetchPosts() {
let resp = this.summaryService.getAllSummery()
this.sub = resp.subscribe((res: Isummary[]) => {
this.summaryArray = res
});
}
界面
export interface Isummary {
toto:string[],
foo:string[]
}
html
<div*ngFor="let post of summaryArray | keyvalue">
<span>{{post.key}}</span>
<span *ngfor="let value of post.value">{{ value }}</span>
</div>
最佳答案
您可以使用 KeyValuePipe而且您不必更改对象中的任何内容
export interface Isummary {
toto: string[];
foo: string[];
}
@Component({
selector: "example",
template: `
<div *ngFor="let item of object | keyvalue">
<span>key: {{ item.key }}</span>
<span>Values</span>
<span *ngFor="let value of item.value">{{ value }}</span>
</div>
`,
})
export class ExampleComponent {
object: Isummary = {
toto: ["titi", "tata"],
foo: ["foobar", "footix"],
};
}
或者您可以使用 Object.entries
@Component({
selector: "example",
template: `<div *ngFor="let item of object">
<span>key: {{ item[0] }}</span>
<span>Values</span>
<span *ngFor="let value of item[1]">{{ value }}</span>
</div>`,
})
export class ExampleComponent {
object = Object.entries({
toto: ["titi", "tata"],
foo: ["foobar", "footix"],
});
}
关于Angular 将对象转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68314022/