To answer your question:
function printPrice(obj) {
if (obj.price)
console.log(obj.name, obj.price)
else for (key in obj)
printPrice(obj[key])
}
var obj = {
"bakery1": {
"small": {
"name": "Small cookie",
"price": 0.75
},
"large": {
"name": "Large cookie",
"price": 3
}
},
"bakery2": {
"small": {
"name": "Small cookie",
"price": 1
},
"large": {
"name": "Large cookie",
"price": 4
}
}
};
printPrice(obj)
However, for these kinds of collections, it might be better to use an array. For example, we could do something like this:
var bakeries = [
{
name: 'Bakery 1',
menu: [
{name: 'small cookie', price: 0.75},
{name: 'large cookie', price: 3.00}
]
},
{
name: 'Bakery 2',
menu: [
{name: 'small cookie', price: 1.00},
{name: 'large cookie', price: 4.00}
]
}
]
This enables us to better organize the specific properties of each item. In this case, the code to print the prices becomes much simpler:
bakeries
.map(bakery => bakery.menu)
.forEach(menu => menu.map(
item => console.log(item.name, item.price)))