Arrays, objects and JSON · Frontend: HTML, CSS and JavaScript
How do you work with lists of things, like the products in a shop?
Course contentsWhy you need it
Nearly all data a page shows arrives as arrays of objects: products, messages, search results. Turning that data into what's on screen means filtering it, transforming it and adding it up, and filter, map and reduce do exactly that in one readable line each.
The intuition
An object groups named values; an array is an ordered list:
const lamp = { name: "Lamp", price: 30 };
const prices = [30, 120, 45];Read a value with a dot: lamp.price; an item by position: prices[0].
Array methods take a small function and apply it to every item, returning something new (the original array is untouched):
| Method | Returns |
|---|---|
filter(x => test) | the items where the test is true |
map(x => newValue) | one new value per item |
reduce((acc, x) => …, start) | one value built from all items |
find(x => test) | the first match, or undefined |
... (spread) copies: [...list, item] is a new array with one more item, { ...obj, price: 9 } a new object with one field changed.
JSON is how objects travel over the network: JSON.stringify(obj) turns an object into text, JSON.parse(text) turns it back.
Definition
Array method
A function such as filter, map or reduce that walks the array for you and returns a new result.
Spread (...)
Copies the items of an array or the fields of an object into a new one.
JSON
A text format for data: objects in { }, arrays in [ ], strings in double quotes. APIs send and receive it.
Examples
Filter, then map
Try it yourselfKeep the products in stock, then keep just their names.
const products = [
{ name: "Lamp", price: 30, inStock: true },
{ name: "Desk", price: 120, inStock: false },
{ name: "Chair", price: 45, inStock: true },
];
const available = products.filter(p => p.inStock);
const names = available.map(p => p.name);
console.log(names);
console.log(products[1].price);[ 'Lamp', 'Chair' ] 120
- L6Keeps Lamp and Chair: the items where p.inStock is true.
- L7Turns each product into just its name.
- L8Strings inside an array print with quotes.
[ 'Lamp', 'Chair' ] - L9The original array still has all three; index 1 is the desk.
120
Add it all up
Try it yourselfreduce carries a running total from item to item.
const prices = [30, 120, 45];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total);
console.log(Math.max(...prices));195 120
- L2sum starts at 0, then 0+30, 30+120, 150+45.
195 - L4...prices spreads the array into separate arguments: Math.max(30, 120, 45).
120
Copies and JSON
Try it yourselfChange a copy, not the original, and turn objects into text.
const user = { name: "Ada", city: "London" };
const moved = { ...user, city: "Paris" };
console.log(user.city, moved.city);
const { name, city } = moved;
console.log(name, city);
const text = JSON.stringify(moved);
console.log(text);
console.log(JSON.parse(text).name);London Paris
Ada Paris
{"name":"Ada","city":"Paris"}
Ada
- L2A new object: every field of user, then city replaced.
- L3The original is untouched.
London Paris - L5Destructuring pulls fields out into variables.
- L8JSON text: keys and strings in double quotes.
{"name":"Ada","city":"Paris"}
Common mistakes
Braces without return
x => x * 2 returns the value, but x => { x * 2 } returns nothing (undefined). With braces, write return.
sort() sorts as text
[10, 9, 1].sort() gives [1, 10, 9]. For numbers pass a compare function: .sort((a, b) => a - b).
Comparing objects with ===
{a: 1} === {a: 1} is false: === on objects asks "is it the same object?", not "same contents?".
Quick quiz
1. What does this print?
const doubled = [1, 2, 3].map(x => { x * 2 });
console.log(doubled);Show the answer
Answer: B
The braces make a function body with no return, so every item becomes undefined.
2. What does this print?
console.log([10, 9, 1].sort());Show the answer
Answer: B
Without a compare function, sort compares text: "10" comes before "9" because "1" < "9".
Practice
3 exercises in three steps: predict what a program prints, change a program to meet a new requirement, then write one from scratch. Your code runs in the browser and is checked the moment you submit.
- PredictWhat's in the cart?
Type exactly what this prints.
- ModifyNames of active users
activeNamesshould return the names of the active users, but it returns a list ofundefined. Fix it. - WriteTotal per customer
Write
totalsByCustomer(orders). Each order looks like{ customer: "ann", amount: 20 }. Return an object with each customer's total:totalsByCustomer([ { customer: "ann", amount: 20 }, { customer: "bo", amount: 5 }, { customer: "ann", amount: 10 }, ]) // { ann: 30, bo: 5 }
Practise this lesson
Open the interactive lesson to edit and run these examples and solve the exercises with instant feedback. Free to start, no sign-up.
Interactive lessons open in order. If you have not done the earlier ones yet, you start at the course map.
Terms in this lesson
| Term | Chinese | Definition |
|---|---|---|
| Array | 数组 | An ordered list of values: [1, 2, 3]. |
| Object | 对象 | Named values grouped together: { name: "Ada" }. |
| JSON | JSON | A text format for data, used by almost every web API. |
| Spread | 展开运算符 | ... copies the items of an array or the fields of an object. |