TutreNews Learn

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.name or user["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?.city gives 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

  1. stringify turns the object into text.
  2. parse turns it back into a new object.
  3. 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