From Zero to Senior · The LabالعربيةGitHub

Chapter 11

Objects and JSON

5 examples · 3 projects · 5 exercises

In this chapter you will learn to

  • describe real things with objects: properties and values
  • read, change and add properties
  • work with arrays of objects using filter, find and map
  • unpack and copy objects with destructuring and spread
  • turn objects into JSON text and back, and build a shopping cart

Examples

11.1 Creating and reading objects

An object is written with curly brackets. Inside are properties: pairs of a name (the key) and a value, separated by a colon, with commas between the pairs:

object.js⤓ File
const book = {
  title: "Code from Zero",
  pages: 340,
  inStock: true,
  tags: ["beginners", "javascript"],
};

console.log(book.title);
console.log(book["pages"]);
console.log(book.tags[0]);

book.pages = 352;
book.price = 25;
console.log(book);
Recorded output$ node object.js
Code from Zero
340
beginners
{
  title: 'Code from Zero',
  pages: 352,
  inStock: true,
  tags: [ 'beginners', 'javascript' ],
  price: 25
}

11.2 Arrays of objects

The most common shape of data in real programs is an array of objects: a list of products, of users, of messages, of matches. Each object has the same keys:

products.js⤓ File
const products = [
  { id: 1, name: "Code from Zero", price: 25, category: "book" },
  { id: 2, name: "Bit mug", price: 8, category: "mug" },
  { id: 3, name: "Senior Frontend", price: 30, category: "book" },
  { id: 4, name: "Bit sticker", price: 3, category: "sticker" },
];

const books = products.filter((p) => p.category === "book");
console.log(books.map((p) => p.name));

const found = products.find((p) => p.id === 2);
console.log(found.name, found.price);

const cheapest = products.reduce((a, b) => (b.price < a.price ? b : a));
console.log(cheapest.name);
Recorded output$ node products.js
[ 'Code from Zero', 'Senior Frontend' ]
Bit mug 8
Bit sticker

11.3 Destructuring and spread

Two short syntaxes appear everywhere in modern JavaScript:

destructure.js⤓ File
const visitor = { name: "Sara", age: 34, city: "Alexandria" };

const { name, city } = visitor;
console.log(`${name} lives in ${city}`);

const copy = { ...visitor, age: 35 };
console.log(visitor.age, copy.age);
Recorded output$ node destructure.js
Sara lives in Alexandria
34 35

11.4 JSON: objects as text

Objects live in a program’s memory. But how do you save one to a file, or send it from a server to a browser on the other side of the world? You turn it into text. The standard text format for data on the web is JSON (JavaScript Object Notation), and it looks almost exactly like a JavaScript object:

json.js⤓ File
const order = { id: 501, items: ["book", "mug"], paid: false };

const text = JSON.stringify(order);
console.log(text);
console.log(typeof text);

const back = JSON.parse('{"id":502,"items":["sticker"],"paid":true}');
console.log(back.items[0], back.paid);
Recorded output$ node json.js
{"id":501,"items":["book","mug"],"paid":false}
string
sticker true

11.5 Project: a shopping cart

Let us build the logic of an online shop’s cart: a catalogue of products, a cart that remembers which products and how many, and functions that add items and calculate totals. This is the same logic that runs behind real shops, just smaller:

cart.js⤓ File
const catalog = [
  { id: 1, name: "Code from Zero", price: 25 },
  { id: 2, name: "Bit mug", price: 8 },
  { id: 3, name: "Bit sticker", price: 3 },
];

const cart = [];

function addToCart(productId, quantity = 1) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity += quantity;
  } else {
    cart.push({ productId, quantity });
  }
}

function lineTotal(item) {
  const product = catalog.find((p) => p.id === item.productId);
  return product.price * item.quantity;
}

function cartTotal() {
  return cart.reduce((sum, item) => sum + lineTotal(item), 0);
}

addToCart(1);
addToCart(3, 4);
addToCart(1);

for (const item of cart) {
  const product = catalog.find((p) => p.id === item.productId);
  console.log(`${product.name} × ${item.quantity} = ${lineTotal(item)}`);
}
console.log(`Total: ${cartTotal()}`);

// Ready to save or send to a server
console.log(JSON.stringify(cart));
Recorded output$ node cart.js
Code from Zero × 2 = 50
Bit sticker × 4 = 12
Total: 62
[{"productId":1,"quantity":2},{"productId":3,"quantity":4}]

Practice projects

Project 11.1 · Easy

A library card for your favourite book

Describe one book as an object, change it, add to it, and print every property it has.

You will practise: object literals, changing and adding properties, Object.entries and Object.keys.

Steps
  1. Create a book object with title, author, pages and read: false.
  2. You have just finished it: set book.read to true.
  3. Add a property that did not exist before: book.rating = 5.
  4. Loop over Object.entries(book) with for (const [key, value] of …) and print each pair.
  5. Print how many properties the object has now with Object.keys(book).length.

Hint: Object.entries turns an object into an array of [key, value] pairs, and the square brackets in the loop unpack each pair into two variables.

Solution
book-card.js⤓ File
const book = {
  title: "The Little Prince",
  author: "Antoine de Saint-Exupéry",
  pages: 312,
  read: false,
};

book.read = true;
book.rating = 5;

for (const [key, value] of Object.entries(book)) {
  console.log(key + ":", value);
}
console.log("Properties:", Object.keys(book).length);
Recorded output$ node book-card.js
title: The Little Prince
author: Antoine de Saint-Exupéry
pages: 312
read: true
rating: 5
Properties: 5

Project 11.2 · Medium

The class report

Keep a list of students and their marks, print each student’s average, and find the top of the class.

You will practise: arrays of objects, destructuring in a loop, a helper function, and tracking the best value so far.

Steps
  1. Create an array students: each item is { name, marks }, where marks is an array of three numbers.
  2. Write average(marks) using reduce and Math.round.
  3. Loop with for (const { name, marks } of students) and print each name with its average.
  4. Keep a variable best, starting at null. Replace it with { name, avg } whenever a student beats it.
  5. After the loop, print the winner. Then change the marks so a different student wins, and check that the report follows.

Hint: { name, avg } is a shortcut for { name: name, avg: avg }. When a variable has the same name as the property, you write it once.

Solution
grades.js⤓ File
const students = [
  { name: "Mona", marks: [90, 85, 100] },
  { name: "Omar", marks: [70, 65, 80] },
  { name: "Sara", marks: [95, 92, 97] },
];

function average(marks) {
  const total = marks.reduce((sum, mark) => sum + mark, 0);
  return Math.round(total / marks.length);
}

let best = null;
for (const { name, marks } of students) {
  const avg = average(marks);
  console.log(name, "→", avg);
  if (best === null || avg > best.avg) best = { name, avg };
}
console.log("Top of the class:", best.name, "(" + best.avg + ")");
Recorded output$ node grades.js
Mona → 92
Omar → 72
Sara → 95
Top of the class: Sara (95)

Project 11.3 · Challenge

App settings saved as JSON

Real apps start from default settings, load what the user saved last time, apply a change, and save the result again. Build that cycle.

You will practise: JSON.parse, JSON.stringify with indentation, and merging objects with spread without changing the originals.

Steps
  1. Create defaults with theme, fontSize and language.
  2. Pretend the app saved this text last time: '{"theme":"dark","fontSize":18}'. Notice that it has no language.
  3. Merge them: { ...defaults, ...JSON.parse(saved) }. Later properties win, so the saved values replace the defaults, and the missing ones keep their defaults.
  4. The user makes the text bigger: create updated with spread and fontSize + 2. Print both sizes to prove settings did not change.
  5. Turn updated back into text with JSON.stringify(updated, null, 2), ready to be saved.

Hint: the order inside the braces matters. Swap the two spreads and the defaults would wipe out what the user saved, a very common bug.

Solution
settings.js⤓ File
const defaults = { theme: "light", fontSize: 16, language: "en" };

// What the app stored last time, as JSON text
const saved = '{"theme":"dark","fontSize":18}';

const settings = { ...defaults, ...JSON.parse(saved) };
console.log(settings);

const updated = { ...settings, fontSize: settings.fontSize + 2 };
console.log("Before:", settings.fontSize, "after:", updated.fontSize);

const text = JSON.stringify(updated, null, 2);
console.log(text);
Recorded output$ node settings.js
{ theme: 'dark', fontSize: 18, language: 'en' }
Before: 18 after: 20
{
  "theme": "dark",
  "fontSize": 20,
  "language": "en"
}

Exercises

Exercise 11.1 · Easy

Create an object describing your favourite film, with at least five properties, one of them an array. Print it with console.log and with JSON.stringify(film, null, 2).
The book's short answer
Any object with five properties, such as title, year, director, rating and an array actors.
Show the solution
film.js⤓ File
const film = {
  title: "The Message",
  year: 1976,
  director: "Moustapha Akkad",
  rating: 8.1,
  languages: ["Arabic", "English"],
  actors: ["Anthony Quinn", "Irene Papas", "Abdullah Gaith"],
};

console.log(film);
console.log(JSON.stringify(film, null, 2));

// Reading single properties, and an item of the array:
console.log(`${film.title} (${film.year}), ${film.actors.length} actors, starring ${film.actors[0]}`);
Recorded output$ node film.js
{
  title: 'The Message',
  year: 1976,
  director: 'Moustapha Akkad',
  rating: 8.1,
  languages: [ 'Arabic', 'English' ],
  actors: [ 'Anthony Quinn', 'Irene Papas', 'Abdullah Gaith' ]
}
{
  "title": "The Message",
  "year": 1976,
  "director": "Moustapha Akkad",
  "rating": 8.1,
  "languages": [
    "Arabic",
    "English"
  ],
  "actors": [
    "Anthony Quinn",
    "Irene Papas",
    "Abdullah Gaith"
  ]
}
The Message (1976), 3 actors, starring Anthony Quinn

Exercise 11.2 · Easy

In products.js, print the names of all products cheaper than 10.
The book's short answer
products.filter((p) => p.price < 10).map((p) => p.name)
Show the solution
cheap.js⤓ File
const products = [
  { id: 1, name: "Code from Zero", price: 25, category: "book" },
  { id: 2, name: "Bit mug", price: 8, category: "mug" },
  { id: 3, name: "Senior Frontend", price: 30, category: "book" },
  { id: 4, name: "Bit sticker", price: 3, category: "sticker" },
];

const cheap = products.filter((p) => p.price < 10).map((p) => p.name);
console.log(cheap);
Recorded output$ node cheap.js
[ 'Bit mug', 'Bit sticker' ]

Exercise 11.3 · Medium

Add a function removeFromCart(productId) to the cart. (Hint: search MDN for findIndex and splice, or build a new array with filter.)
The book's short answer
function removeFromCart(id) { const i = cart.findIndex((item) => item.productId === id); if (i !== -1) cart.splice(i, 1); }
Show the solution
remove.js⤓ File
const catalog = [
  { id: 1, name: "Code from Zero", price: 25 },
  { id: 2, name: "Bit mug", price: 8 },
  { id: 3, name: "Bit sticker", price: 3 },
];

let cart = [];

function addToCart(productId, quantity = 1) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity += quantity;
  } else {
    cart.push({ productId, quantity });
  }
}

// Way 1: find the line's position and cut it out of the array (changes the array itself).
function removeFromCart(productId) {
  const i = cart.findIndex((item) => item.productId === productId);
  if (i !== -1) {
    cart.splice(i, 1);
  }
}

// Way 2: build a new array without that product.
function removeFromCartWithFilter(productId) {
  cart = cart.filter((item) => item.productId !== productId);
}

addToCart(1);
addToCart(2);
addToCart(3, 4);
console.log(JSON.stringify(cart));

removeFromCart(2);
console.log(JSON.stringify(cart));

removeFromCartWithFilter(1);
console.log(JSON.stringify(cart));

removeFromCart(99); // not in the cart: nothing happens, and no error
console.log(JSON.stringify(cart));
Recorded output$ node remove.js
[{"productId":1,"quantity":1},{"productId":2,"quantity":1},{"productId":3,"quantity":4}]
[{"productId":1,"quantity":1},{"productId":3,"quantity":4}]
[{"productId":3,"quantity":4}]
[{"productId":3,"quantity":4}]

Exercise 11.4 · Medium

Give products a discount property (for example 0.1 for 10%) and change lineTotal to use it.
The book's short answer
return product.price * (1 - (product.discount ?? 0)) * item.quantity; (or || 0).
Show the solution
discount.js⤓ File
const catalog = [
  { id: 1, name: "Code from Zero", price: 25, discount: 0.1 },
  { id: 2, name: "Bit mug", price: 8 },
  { id: 3, name: "Bit sticker", price: 3, discount: 0.5 },
];

const cart = [
  { productId: 1, quantity: 2 },
  { productId: 2, quantity: 1 },
  { productId: 3, quantity: 4 },
];

function lineTotal(item) {
  const product = catalog.find((p) => p.id === item.productId);
  // ?? gives 0 when a product has no discount (undefined).
  return product.price * (1 - (product.discount ?? 0)) * item.quantity;
}

for (const item of cart) {
  const product = catalog.find((p) => p.id === item.productId);
  console.log(`${product.name} × ${item.quantity} = ${lineTotal(item)}`);
}
console.log(`Total: ${cart.reduce((sum, item) => sum + lineTotal(item), 0)}`);
Recorded output$ node discount.js
Code from Zero × 2 = 45
Bit mug × 1 = 8
Bit sticker × 4 = 6
Total: 59

Exercise 11.5 · Challenge

Write receipt(), which returns the whole receipt as one string, with one line per item and the total, using map and join("\n").
The book's short answer
Map each cart item to a line of text, add the total line, and join("\n").
Show the solution
receipt.js⤓ File
const catalog = [
  { id: 1, name: "Code from Zero", price: 25 },
  { id: 2, name: "Bit mug", price: 8 },
  { id: 3, name: "Bit sticker", price: 3 },
];

const cart = [
  { productId: 1, quantity: 2 },
  { productId: 3, quantity: 4 },
];

function lineTotal(item) {
  const product = catalog.find((p) => p.id === item.productId);
  return product.price * item.quantity;
}

function cartTotal() {
  return cart.reduce((sum, item) => sum + lineTotal(item), 0);
}

// One line per item, then the total, joined into one string.
function receipt() {
  const lines = cart.map((item) => {
    const product = catalog.find((p) => p.id === item.productId);
    return `${product.name} × ${item.quantity} = ${lineTotal(item)}`;
  });
  lines.push(`Total: ${cartTotal()}`);
  return lines.join("\n");
}

const text = receipt();
console.log(text);
console.log(typeof text); // one string, ready to save, print or send
Recorded output$ node receipt.js
Code from Zero × 2 = 50
Bit sticker × 4 = 12
Total: 62
string