1

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?

1 Answer 1

2

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"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.