Arrays and objects
Objects and JSON
Goal: Model data with objects, destructuring and JSON · 10 min
An object groups named properties: const user = { name: "Ada", age: 36 };
- Read:
user.nameoruser["name"](brackets for dynamic keys). - Add/change:
user.city = "London";— delete:delete user.age. Object.keys(o),Object.values(o),Object.entries(o)list contents.- Destructuring:
const { name, age } = user; - Spread copies:
const older = { ...user, age: 37 }; - Optional chaining:
user.address?.citygives undefined instead of an error.
JSON is the text format for exchanging data: JSON.stringify(obj) → string, JSON.parse(text) → object. Keys must be in double quotes in JSON.
Worked example: Round trip through JSON
- stringify turns the object into text.
- parse turns it back into a new object.
- The copy is independent of the original.
const book = { title: "Faust", year: 1808 };
const text = JSON.stringify(book);
console.log(text);
console.log(JSON.parse(text).year + 1);Output:
{"title":"Faust","year":1808}
1809