Reference · module 5
Objects
Everything this module explains, on one page.
Objects
Group named values in one object and read them back.
- const user = { name: "Ana", age: 31 }; is an object: named values, called properties, in curly braces. Each property is a key, a colon and a value.
- user.name reads a property with a dot. user["name"] does the same with a string, which you need when the key is in a variable: user[key] reads whatever key holds.
- Reading a property that does not exist gives undefined, not an error. But reading a property of undefined itself, like user.address.city, stops with a TypeError.
The mistake you are about to make
user.key
user[key]
The dot looks shorter and more familiar. user.key looks for a property literally named "key", not the one stored in the variable key, and quietly returns undefined.
Changing and copying objects
Change properties, list them, and copy an object instead of sharing it.
- user.age = 32; changes a property and user.city = "Oslo"; adds a new one. delete user.city; removes it. All of this works on a const object, just like push on a const array.
- Object.keys(user) gives an array of the property names, like ["name", "age"]. Object.values gives the values, and for (const key of Object.keys(user)) walks over the properties.
- const b = a; does not copy an object. Both names point at the same object, so b.x = 5 changes a.x as well. To copy, write const b = { ...a };.
The mistake you are about to make
const copy = settings; copy.theme = "dark";
const copy = { ...settings }; copy.theme = "dark";
It looks like = makes a second, independent variable. For an object it is a second name for the same thing: the theme changes in the original settings too.
Arrays of objects and JSON
Work with real-looking data: lists of records, unpacking, and JSON text.
- Real data is usually an array of objects: const users = [{ name: "Ana", age: 31 }, { name: "Bo", age: 25 }]; users[1].name is "Bo" — first the index, then the property.
- Destructuring unpacks properties into variables: const { name, age } = user; creates name and age at once. For arrays it goes by position: const [first, second] = list;.
- JSON is text that looks like an object. JSON.stringify(user) turns an object into such text for sending or saving, and JSON.parse(text) turns it back into an object.
The mistake you are about to make
const data = '{"n": 1}'; console.log(data.n);
const data = JSON.parse('{"n": 1}'); console.log(data.n);
JSON text looks exactly like an object, so you reach for its properties. It is still a string: data.n is undefined until the text goes through JSON.parse.