如何遍历Typescript中的复杂对象?

时间:2018-07-30 12:42:29

标签: json typescript

我有一个这样声明的Typescript对象:

export class MockData {
    public static food = {
        "cake": {
            "name": "donut",
            "price": "1.5€",
            "ingredients": {
                "base": "biscuit",
                "batter": [{
                    "id": "1002",
                    "type": "Chocolate"
                },
                {
                    "id": "1003",
                    "type": "Blueberry"
                }
                ],
                "toppings": [{
                    "id": "5002",
                    "type": "Glazed"
                },
                {
                    "id": "5004",
                    "type": "Maple"
                }
                ]
            },
            "baking_time": "2h"
        }
    };
}

然后,从另一个类中,我想遍历ingredients的属性来访问basebattertoppings,就好像它们也是对象一样(能够以相同的方式访问batter元素)。我已经尝试过了:

Object.keys(MockData.food.cake).forEach( element => {
        console.log(element);
});

还有:

for(let prop in MockConversation.conversation.cake){
    if(1){ // Test condition
        console.log(prop);
    }
}

但是,由于此原因,我只能获取namepriceingredientsbaking_time作为字符串,因此无法访问它们的内部属性。我该怎么做?

1 个答案:

答案 0 :(得分:1)

在此循环中,您迭代键。因此,在登录时会显示密钥本身。如果您想要该值,则可以这样实现:

Object.keys(MockData.food.cake).forEach(key => {
        console.log(MockData.food.cake[key]);
});

这样,您将获得:donut1.5€2h,并将配料表作为对象:

{
    "base": "biscuit",
    "batter": [{
        "id": "1002",
        "type": "Chocolate"
    },
    {
        "id": "1003",
        "type": "Blueberry"
    }
    ],
    "toppings": [{
        "id": "5002",
        "type": "Glazed"
    },
    {
        "id": "5004",
        "type": "Maple"
    }
    ]
}

但是如果您想访问basebattertoppings,并且如果您的数据结构允许,那么直接访问会更容易:

const ing = MockData.food.cake.ingredients;

console.log(ing.base);

Object.keys(ing.batter).forEach(key => {
        console.log(ing.batter[key]);
});

Object.keys(ing.toppings).forEach(key => {
        console.log(ing.toppings[key]);
});

输出:

biscuit
{id: "1002", type: "Chocolate"}
{id: "1003", type: "Blueberry"}
{id: "5002", type: "Glazed"}
{id: "5004", type: "Maple"}