Menu
Coddy logo textTech

Nested JSON

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 23 of 65.

A JSON object can hold another JSON object inside it. It can be infinitely nested. For example:

const userData = {
  "user": {
    "name": "Kim",
    "address": {
      "city": "Springfield",
      "zip": 12345,
      "location": {
        "coordinates": {
          "latitude": 42.1234,
          "longitude": -71.5678
        }
      }
    }
  }
}

To access a nested key we would write:

userData.user.name
userData.user.address.location
// And so on
challenge icon

Challenge

Easy

Create a function named calculateRestaurantBill that takes a JSON object representing a restaurant order as input. Each key in the object is a dish name, and each value is another object containing:

  • price (number)
  • quantity (number)
  • isSpecialOffer (boolean) 

if true, there's a 20% discount on that dish The function should:

  1. Calculate the total bill
  2. Apply any special offer discounts

The returned object contains:

  • totalBeforeDiscount
  • totalDiscount
  • finalTotal

(All values are rounded to 2 decimal places)

Cheat sheet

JSON objects can be nested infinitely deep:

const userData = {
  "user": {
    "name": "Kim",
    "address": {
      "city": "Springfield",
      "zip": 12345,
      "location": {
        "coordinates": {
          "latitude": 42.1234,
          "longitude": -71.5678
        }
      }
    }
  }
}

Access nested properties using dot notation:

userData.user.name
userData.user.address.location
// And so on

Try it yourself

function calculateRestaurantBill(order) {
    // Write code here
    
    
    return {
        totalBeforeDiscount: Number(totalBeforeDiscount.toFixed(2)),
        totalDiscount: Number(totalDiscount.toFixed(2)),
        finalTotal: Number(finalTotal.toFixed(2))
    };
}
// Do not write anything outside function
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow