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>
2 Answers 2
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"],
});
}
5 Comments
the const object: Isummary = { toto: ["titi", "tata"], foo: ["foobar", "footix"], }; because the data comes from a json that I call via a service and there is a lot of data in the real json I can't put it like that right?The answer of @Chris is the Angular way of doing it. Here is another approach from the js only side.
Assume we have:
{
"toto": [
"titi",
"tata"
],
"foo": [
"foobar",
"footix"
]
}
You can use this, to transform it into an array:
const toArray = (data) => {
return Object.keys(data).map(key => data[key]);
}
In the end it should look like this:
[
[
"titi",
"tata"
],
[
"foobar",
"footix"
]
]
summaryArray's type isIsummary[]which an object type. So you are trying to loop on a Object Array, I guess it's normal if it display "object Object" in your html. If you want to display values which are inside, try with a second ngFor and use keyvalue pipe : angular.io/api/common/KeyValuePipe