Lesson 8 of 28
In progress
Arrays and objects together
Store lists in arrays and records in objects, then combine them into the shape most real data uses.
An array is an ordered list; an object is a bag of named values. Most application data is an array of objects, and knowing how to read, update and copy that shape covers a huge amount of daily work.
What you will learn
- Create and read arrays and objects.
- Add, update and remove entries without mutating shared data.
- Loop over an array of objects and summarise it.
Arrays
Editable. Runs in your browser.
console.log(scores[0]);
console.log(scores.length);
console.log(scores.at(-1));
scores.push(65);
console.log(scores);
scores.splice(1, 1);
console.log(scores);
Press Run to see the output.
push adds to the end, pop removes from the end, shift and unshift work at the start. splice(index, count) removes items in place and returns them. at(-1) reads the last item without arithmetic.
Arrays are objects, so typeof says "object". Use Array.isArray(value) to test.
Iteration forms from lesson 7 apply directly: for...of for values, entries() for index and value.
Objects
Editable. Runs in your browser.
console.log(user.name);
console.log(user["role"]);
console.log(Object.keys(user));
console.log(user.scores.length);
Press Run to see the output.
Dot notation is for fixed names. Bracket notation is for names held in variables or containing spaces. Reading a missing property gives undefined, not an error; reading a property of undefined throws.
in checks whether a key exists, including inherited ones. Object.hasOwn(user, "name") checks own properties, which is usually what you mean.
Adding, updating, removing
Editable. Runs in your browser.
user.role = "editor";
user["active"] = true;
delete user.active;
console.log(user);
Press Run to see the output.
Mutation is fine for a local object you own. It is a problem when the object is shared, because another part of the program may be relying on the old shape. Copy before changing shared data:
Editable. Runs in your browser.
console.log(original.role);
console.log(promoted.role);
Press Run to see the output.
Spread copies the top level. Nested objects are still shared, so a deep change needs a deep copy or an explicit nested spread.
Array of objects
This is the shape of almost every API response and every list in an interface.
Editable. Runs in your browser.
let total = 0;
const merit = [];
for (const student of students) {
total += student.score;
if (student.score >= 85) {
merit.push(student.name);
}
}
console.log("Average:", total / students.length);
console.log("Merit:", merit);
Press Run to see the output.
Read the accessors from the outside in: students[0] is one object, .name takes its property. When looping, the loop variable already is the object, so student.name is enough. Print the number of records as well as the average: a missing score changes the average while the count you expected stays the same, and only the length exposes it, which is why the count belongs in the report next to the total.
Finding and filtering
Editable. Runs in your browser.
const ravi = students.find((student) => student.name === "Ravi");
console.log(ravi?.score);
const passing = students.filter((student) => student.score >= 80);
console.log(passing.length);
Press Run to see the output.
find returns the first match or undefined; filter always returns an array. Optional chaining ?. keeps a missing result from throwing when you read a property.
findIndex returns the position, which is what you need before replacing or removing an item by identity.
Copying nested data
Spread is shallow, so an object containing an array still shares that array. structuredClone(value) makes a deep copy of plain data and is built into modern browsers.
Editable. Runs in your browser.
shallow.tags.push("editor");
console.log(original.tags);
console.log(deep.tags);
Press Run to see the output.
The shallow copy shares the tags array, so pushing through it changes the original. The deep clone does not. structuredClone cannot copy functions or DOM nodes, which is a fair limit: those should not be in data you are cloning anyway.
Destructuring, a preview
Editable. Runs in your browser.
console.log(name, score, first, second);
Press Run to see the output.
Destructuring pulls named properties or positions into variables. Module 5 covers defaults, renaming and nested patterns.
const copy = original does not copy an object or array; it copies the reference. Changing copy.name changes original.name. Use { ...original } for objects and [...array] for arrays when you need an independent top level.
Given an array of products with name, price and stock, print the names of products under 100 that are in stock, and the total value of all stock (price multiplied by stock). Use a loop and then rewrite the total with reduce.
Show solution
Editable. Runs in your browser.
const affordable = products.filter((p) => p.price < 100 && p.stock > 0);
console.log(affordable.map((p) => p.name));
const value = products.reduce((sum, p) => sum + p.price * p.stock, 0);
console.log(value);
Press Run to see the output.
The filter keeps only items that meet both conditions, and the reduce multiplies before adding. The initial value 0 matters: without it, the first product becomes the accumulator and the result is wrong.
Recap
- Arrays are ordered and zero-indexed; objects map names to values.
- Spread copies one level, so nested data needs care.
- An array of objects is the standard shape for lists;
find,filterandreducedo most of the work.
You have finished control flow and functions. Next, you will change the page itself by selecting and updating elements.
When should I use a Map instead of an object?
Why does JSON.stringify drop some properties?
Progress is saved in this browser only. No account, no email.