4

How I could render an object of objects in Angular but without turn it in an array or anything similar. The reason for this is that I have a large object of objects and I would like to avoid to many iterations from object to an array after that to loop the array in the html.

For example I have:

    persons: any = {
      0: { name: 'name1', email: '[email protected]' },
      1: { name: 'name2', email: '[email protected]' },
      2: { name: 'name3', email: '[email protected]' }
    }

When I do is the following:

    <div *ngFor="let person of persons | keyvalue">
      <p>
      {{ person.key }} / {{ person.value }}
      </p>
    </div>

The result is:

    0 / [object Object]
    1 / [object Object]
    2 / [object Object]

I tried to loop one more time thru the person.value:

    <div *ngFor="let person of persons | keyvalue;">
      <p>
      {{ person.key }}
      <span *ngFor="let item of person.value | keyvalue"></span>
      </p>
    </div>

but this causing an error ("No overload matches this call.").

Could anyone tell me how could I achieve this?

0

2 Answers 2

5

You can just use the json pipe

example:

{{persons | json}}

Documentation: https://angular.io/api/common/JsonPipe

Stackblitz example

Sign up to request clarification or add additional context in comments.

2 Comments

I don't need exactly this but the example that you provided in the comment of Jeremy Thille is working and it is exactly what I tried to do. I tried with {{ person.value.name }} but the correct way was {{ person.value['name'] }}. Thank you.
Glad I could help :-)
2

The keyvalue pipe transforms 0: { name: 'name1', email: '[email protected]' } into { key : 0, value : { name: 'name1', email: '[email protected]' }}. So you should be able to do :

<div *ngFor="let person of persons | keyvalue">
   <p>
      {{ person.value.name}} / {{ person.value.email }}
   </p>
</div>

3 Comments

I already tried this but forgot to mention it. The result is an error.
In the example that eko provided it is working: <p>{{ person.value['name'] }} / {{ person.value['email'] }}</p> Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.