Ninius86
Ninius86

Reputation: 295

How to iterate over nested JSON in Angular

I'm using Angular7 and ngx-translate.

i18n/en.json looks something like this:

{
    "items": {
        "a1": "first",
        "a2": "second",
        "a3": "third"
    },
    "nesteditems": {
        "n1": {
            "f1": "nested11",
            "f2": "nested12",
            "f3": "nested13"
        },
        "n2": {
            "f1": "nested21",
            "f2": "nested22",
            "f3": "nested23"
        },
        "n3": {
            "f1": "nested31",
            "f2": "nested32",
            "f3": "nested33",
            "f4": "nested34"
        }
    }
}

Is there a way to iterate over "items" and "nesteditems" using ngFor or some other directive to display them?

Upvotes: 0

Views: 477

Answers (1)

Jeffrey Jarry
Jeffrey Jarry

Reputation: 156

You could use the keyvalue pipe in angular 7 twice if you really wanted to stick to iterating over it using ngFor.

<div *ngFor="let item of nesteditems | keyvalue">    
     <div *ngFor="let innerItem of item.value | keyvalue">
      {{innerItem .key}}:{{innerItem .value}}
    </div>
</div>

Now another recommendation would be to consider flattening the nestedItems into an array in some way, now I dont know the shapeof your data so maybe that wouldnt be reasonable though.

Upvotes: 1

Related Questions