Issue
I have a nested object data–
"data": {
"serial": "123",
"def": {
"id": "456",
"data": {
"firstname": "abc",
},
"method": "post",
},
"ghi": {
"id": "456",
"data": {
"amount": "3500.0",
},
"method": "post",
},
"jkl": "done"
}
I stored it in items object.Then,
I tried printing it in my HTML component using-
<div *ngFor="let item of items | keyvalue">
<div>
<div>{{item.key}}:{{item.value}}</div>
</div>
</div>
But the output comes as-
serial: 123
def: [object Object]
ghi: [object Object]
jkl: done
How can I print this nested object?
Thanks in advance !
Solution
I think for an object you may not be able to use *ngFor like the way you use it for arrays. My solution is to use a recursive function like this in your ts file:
expand(data: any): string[] {
let stringArr = [];
for (const prop in data) {
data[prop] instanceof Object
? (stringArr = stringArr.concat([`${prop}: `]).concat(this.expand(data[prop])))
: stringArr.push(`${prop}: ${data[prop]}`);
}
return stringArr;
}
and then in your HTML file:
<div *ngFor = " let item of expand(data)">
{{ item }}
</div>
then it will show this on your page:
serial: 123
def:
id: 456
data:
firstname: abc
method: post
ghi:
id: 456
data:
amount: 3500.0
method: post
jkl: done