Search code examples
javascriptobjectfor-loopnestednested-loops

JavaScript get value from nested object


If this is my object:

var obj = {
bakery1: {
    small: {
        name: "Small cookie",
        price: 0.75;
    }
    large: {
        name: "Large cookie",
        price: 3.00;
    }
}
bakery2: {
    small: {
        name: "Small cookie",
        price: 1.00;
    }
    large: {
        name: "Large cookie",
        price: 4.00;
    }
}
};

How would I go about making a loop that prints every price to the console?

And when this value is printed, is there a way to trace the name?

For example if the output is 3.00 how would I make a function that gives me the name that goes with the 3.00 price?

Thanks in advance!


Solution

  • 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)))