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 onChallenge
EasyCreate 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:
- Calculate the total bill
- 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 onTry 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 functionThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys