0

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 !

2 Answers 2

1

You’re using ngFor which is mainly used for arrays, which you don’t have. I suggest you revise your data or if it does need to stay as an object then simply do: data.def.id for example - no ngFor required.

Another example to get the firstname:

{{data?.def?.data?.firstname}}
Sign up to request clarification or add additional context in comments.

6 Comments

Just saying "refactor your data" is not an answer in my opinion. It's possible the data comes from some system that Atul doesn't control. There are most certainly ways to achieve what @Atul wants. Whether those are easier or harder is another question.
@AndrewJuniorHoward Actually,the data is a response to an API call.So,it can't be modified.
@Atul ok but you've totally missed the second part of my answer . I've stated that you can navigate an object simply by going down the nodes. The accepted answer whilst valid, is overblown. There is no need to use ngFor.
@JorisMolnar I gave 2 answers actually. Both satisfy each outcome
@AndrewJuniorHoward yeah,it worked without having to use *ngFor.But if the data is huge.It becomes hectic to display it manually. Your solution works fine ,if I wanted to access a particular .Thanks for your help :)
|
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.