如何迭代嵌套在Angular 4中的对象中的对象的键?

时间:2017-11-16 12:46:00

标签: angular loops multidimensional-array

变量:

 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": 'info@company.com',
        "items": [
                    {"Beverage":[
                        {"Bigga":'lg'}, 
                        {"Soda":'sm'}, 
                        {"Wata":'fresh'}, 
                        {"Sprite":'codein'}
                    ]},
                    {'Canned':[
                        {"Tuna":'lg'}, 
                        {"Salmon":'sm'}, 
                        {"Mackerel":'fresh'}, 
                        {"Spam":'codein'}   
                    ]}
                ]
        },

这些行显示项目对象的所有键

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

然而,尝试从上面对象的子对象获取值正在显示..&#34; 0 1 2 3 0 1 2 3&#34;

<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>

2 个答案:

答案 0 :(得分:0)

您只获取密钥,而不是与该密钥相关的值

FilterDefinition<BsonDocument> filters = builder.Eq("Address", "XXX") & builder.Eq("CompanyName", "XXXX") & builder.Eq("ContactName", "XXXX");

答案 1 :(得分:0)

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

值是例如store [0] .items,它是一个对象数组,一个集合。

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

所以如果你使用objectKeys(values),你将拥有数组的键,索引。

您需要在数组中迭代才能获取对象,然后使用Object.keys和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>

以获得

Bigga lg 苏打水...