chick3n0x07CC
chick3n0x07CC

Reputation: 798

How to iterate through complex object in Typescript?

I have a Typescript object declared like this:

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"
        }
    };
}

Then, from another class, I want to iterate through ingredientsproperty to access base, batter and toppings as if they were also objects (to be able to access batter elements the same way). I have tried this:

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

and also:

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

But with this, I can only obtain name, price, ingredients and baking_time as strings, so I can't access their internal properties. What could I do to achieve this?

Upvotes: 1

Views: 1556

Answers (1)

milcaepsilon
milcaepsilon

Reputation: 272

On this loop, you iterate on keys. So when logging it, it shows the key itself. If you want the value, you can achieve it like that :

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

this way, you will get : donut, 1.5€, 2h and the ingredients list as an object :

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

but if you want to access to base, batter and toppings and if your data structure permits it maybe it's easier to access directly :

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]);
});

output :

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

Upvotes: 2

Related Questions