Model real records as objects, and convert them to and from JSON text.
Why this matters
Real things have several properties at once. A student has a name, an email and a list of scores; a product has a name, price and stock count. In JavaScript you group related values into an object. When that data travels between a browser and a server, or gets saved to a file, it is written as JSON, a text format based on JavaScript objects. Almost every API you will ever call speaks JSON, so these two ideas go together.
Objects
An object is a set of key: value pairs inside curly braces:
const student = {
name: "Ada",
email: "ada@example.com",
scores: [90, 85, 100],
enrolled: true
};
Read or change properties with a dot, or with square brackets when the key is in a variable:
student.name; // "Ada"
student.scores[0]; // 90
student.enrolled = false; // change a property
student.year = 2; // add a new one
const field = "email";
student[field]; // "ada@example.com"
student.phone; // undefined: no such property
Values can be anything: numbers, strings, arrays, other objects, even functions.
Shorthand and computed values
When a variable already has the name you want for a key, you can write it once:
function makeStudent(name, scores) {
const total = scores.reduce((sum, s) => sum + s, 0);
const average = scores.length ? total / scores.length : 0;
return { name, scores, average }; // same as { name: name, scores: scores, average: average }
}
makeStudent("Grace", [80, 90]);
// { name: "Grace", scores: [80, 90], average: 85 }
Looping over an object
Object.keys(student); // ["name", "email", "scores", "enrolled", "year"]
Object.values(student); // the values
Object.entries(student); // [["name", "Ada"], ["email", ...], ...]
for (const [key, value] of Object.entries(student)) {
console.log(`${key}: ${value}`);
}
Destructuring and spread
Destructuring pulls properties into variables; spread copies an object:
const { name, email } = student; // two new variables
const updated = { ...student, year: 3 }; // copy with one property changed
Spread makes a shallow copy: nested arrays and objects are still shared. That matters when you start writing React, where you should create new objects instead of changing existing ones.
Arrays of objects
Most real data is a list of objects, which is where last lesson's methods shine:
const students = [
makeStudent("Ada", [90, 85, 100]),
makeStudent("Grace", [80, 90]),
makeStudent("Alan", [70, 75])
];
const best = students.reduce((top, s) => (s.average > top.average ? s : top));
best.name; // "Ada"
(reduce without a starting value is fine here because the list is not empty and we want the first student as the starting "best". Check for an empty list before calling it.)
JSON
JSON (JavaScript Object Notation) is a text format that looks almost like an object literal, with stricter rules:
{
"name": "Ada",
"scores": [90, 85, 100],
"enrolled": true,
"mentor": null
}
- Keys must be in double quotes.
- Strings use double quotes only.
- Allowed values: strings, numbers,
true,false,null, arrays and objects. No functions, noundefined, no comments, no trailing commas.
Converting
const text = JSON.stringify(student);
// '{"name":"Ada","email":"ada@example.com",...}' (a string)
const back = JSON.parse(text);
back.name; // "Ada" (a real object again)
JSON.stringify(student, null, 2); // pretty-printed with 2-space indents
JSON.stringify(value)turns an object into a JSON string (to send or save).JSON.parse(text)turns a JSON string into an object (after you receive or load it).
JSON.parse throws a SyntaxError if the text is not valid JSON, for example JSON.parse("{name: 'Ada'}"). You will handle that properly with try/catch in module 4.
A JSON round trip also makes a deep copy of plain data, but it drops functions and undefined and turns dates into strings, so do not rely on it for everything.
Common mistakes
- Treating JSON text as an object.
text.nameisundefineduntil youJSON.parse(text). - Single quotes or unquoted keys in JSON. Valid in JavaScript, invalid in JSON.
- Dividing by zero for an empty list.
0 / 0isNaN; check the length first. - Thinking spread makes a deep copy. Nested arrays are shared.
- Misspelt property names.
student.nmaeis justundefined, with no error, so check spelling when something is unexpectedly undefined.
Quick recap
- Objects group related values under named keys; use dot or bracket access.
Object.keys/values/entries, destructuring and spread are everyday tools.- JSON is text with strict rules;
JSON.stringifywrites it,JSON.parsereads it.
Try it
Open the Do tab: build student objects, parse a JSON list and find the top student.