I have a json that an object I try to transform into an array otherwise when I loop on it I get [object object], in my code I tried something that works but it only shows me the values of each field instead of showing me key => value.
How to display the key and values of my json in my html ? is there a better way to convert an object to an array ?
json
{
"toto": [
"titi",
"tata"
],
"foo": [
"foobar",
"footix"
]
}
ts.file
fetchPosts() {
let resp = this.summaryService.getAllSummery()
this.sub = resp.subscribe((res: Isummary[]) => {
this.summaryArray = res
});
}
interface
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>
You can use the KeyValuePipe and you don't have to change anything in the object
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"],
};
}
or you can use 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"],
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With