FirmCiti Inc
FirmCiti Inc

Reputation: 407

How to iterate keys of an object nested in an object in Angular 4?

Variables:

 objectKeys = Object.keys;
  objectValues = Object.values;

JSON:

@Injectable()
export class DbService {
    db:Database[] = [
        {
        "id":0,
        "img":"../../../assets/img/logo/gro.png",
        "name":"CompName",
        "type":"CompType",
        "hours": "9:00AM-9:00PM",
        "number": 999999,
        "email": '[email protected]',
        "items": [
                    {"Beverage":[
                        {"Bigga":'lg'}, 
                        {"Soda":'sm'}, 
                        {"Wata":'fresh'}, 
                        {"Sprite":'codein'}
                    ]},
                    {'Canned':[
                        {"Tuna":'lg'}, 
                        {"Salmon":'sm'}, 
                        {"Mackerel":'fresh'}, 
                        {"Spam":'codein'}   
                    ]}
                ]
        },

These lines displays all the keys from the item objects

<div *ngFor="let item of store[0].items" class="ai">
        <div *ngFor="let key of objectKeys(item)">{{key}}</div>
    </div>

However trying to get the values from the child object of above object is displaying .."0 1 2 3 0 1 2 3 "

<div *ngFor="let rn of store[0].items" class="items">
            <div *ngFor="let value of objectValues(rn)">
                <div *ngFor="let btn of objectKeys(value)">
                    {{btn}}
                </div>
            </div>
        </div>

Upvotes: 0

Views: 854

Answers (2)

Pierre Mallet
Pierre Mallet

Reputation: 7221

in

 <div *ngFor="let btn of objectKeys(value)">
       {{btn}}
 </div>

value is for exemple for store[0].items, its an array of objects, a collection.

[
   {"Bigga":'lg'}, 
   {"Soda":'sm'}, 
   {"Wata":'fresh'}, 
   {"Sprite":'codein'}
]

so if you use objectKeys(values) you will have keys of the array, the indexes.

you need iterate in the array to get the object, then use Object.keys and Object.value

<div *ngFor="let rn of store[0].items" class="items">
    <div *ngFor="let value of objectValues(rn)">
        <div *ngFor="let item of value">
            {{ objectKeys(item)[0]  }} {{ objectValues(item)[0]  }}
        </div>
    </div>
</div>

in order to get

Bigga lg Soda sm ...

Upvotes: 1

Ivan Mladenov
Ivan Mladenov

Reputation: 1847

You are only getting the keys, not the value associated with that key

<div *ngFor="let rn of store[0].items" class="items">
    <div *ngFor="let value of objectValues(rn)">
        <div *ngFor="let btn of objectKeys(value)">
            {{value[btn]}}
        </div>
    </div>
</div>

Upvotes: 0

Related Questions