Iterate through object leaves in a JavaScript nested object

Let's assume that you have the following nested object tree (e.g. data downloaded from Firebase):

javascript
let menu = {

    1: {
        "Starters": {
            1: {
                "title": "Patatas bravas",
                "desc": "Unas deliciosas bravas con salsa picante",
                "price": 5
            },
            2: {
                "title": "Anchoas",
                "desc": "Recién traídas del cantábrico",
                "price": 7
            }
        }
    },
    2: {
        "First": {
            1: {
                "title": "Canelones de la abuela",
                "desc": "Rellenos de carne, besamel y queso gratinado",
                "price": 12
            },
            2: {
                "title": "Ensalada de queso de cabra",
                "desc": "Olivas, queso de cabra, nueces y un toque de miel",
                "price": 10
            }
        }
    },
    3: {
        "Second": {
            1: {
                "title": "Entrecot a la brasa",
                "desc": "Con guarnición de pimientos del padrón y patatas",
                "price": 25
            }
        }
    }
}

Imagine that you wanted to print the title of every dish on the menu. An option is to iterate through the tree branches using Object.entries().

Example:

javascript
Object.entries(menu).forEach(([menuKey, courses]) => {
    Object.entries(courses).forEach(([courseKey, dishes]) => {
        Object.entries(dishes).forEach(([dishKey, dish]) => {
            console.log(dish.title)
        })
    })
})

Result:

terminal
Patatas bravas
Anchoas
Canelones de la abuela
Ensalada de queso de cabra
Entrecot a la brasa

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.