Objects and JSON
An array stores an ordered list; an object stores named data. It is the natural way to represent things from the real world: a user with name, age and email; a product with price and stock. An object is a collection of key-value pairs, called properties. Keys are texts and values can be of any type, including other objects, arrays and functions.
Creating, reading and modifying properties
They are created with braces. To read a property use dot notation (user.name) or bracket notation (user['name']); brackets are useful when the key is in a variable or has special characters. Assigning to an existing property changes it and assigning to a new one creates it; delete removes it. A function stored in an object is called a method and can use this to access the object itself. If you access a property that does not exist you get undefined, and if you try to read a property of undefined you get a TypeError; optional chaining ?. avoids it.
const user = {
name: 'Lucia',
age: 27,
skills: ['js', 'css'],
address: { city: 'Madrid' },
greet() {
return `Hi, I am ${this.name}`;
}
};
console.log(user.name, user['age']); // Lucia 27
console.log(user.address.city); // Madrid
console.log(user.greet()); // Hi, I am Lucia
console.log(user.phone); // undefined
console.log(user.job?.title); // undefined, no error
user.age = 28; // change
user.email = 'l@x.com'; // create
delete user.skills; // remove
console.log('email' in user); // true
const key = 'name';
console.log(user[key]); // LuciaWalking through objects
Object.keys, Object.values and Object.entries turn the keys, values or pairs of an object into arrays, so you can use everything you learned in week 4. Object.fromEntries does the opposite. Remember also that objects are passed by reference: two variables can point to the same object, and changing one affects the other. To copy use spread or structuredClone.
const stock = { apples: 5, pears: 0, kiwis: 12 };
console.log(Object.keys(stock)); // [ 'apples', 'pears', 'kiwis' ]
console.log(Object.values(stock)); // [ 5, 0, 12 ]
for (const [fruit, qty] of Object.entries(stock)) {
console.log(fruit, qty);
}
const available = Object.fromEntries(
Object.entries(stock).filter(([, qty]) => qty > 0)
);
console.log(available); // { apples: 5, kiwis: 12 }
const alias = stock;
alias.apples = 99;
console.log(stock.apples); // 99 - same objectJSON: objects as text
JSON (JavaScript Object Notation) is a text format for exchanging data between programs, for example between a browser and a server. It looks like a JavaScript object, but it is stricter: keys are always in double quotes, it does not allow comments, functions or undefined, and strings use double quotes. JSON.stringify converts a value into JSON text and JSON.parse converts it back into a value. If the text is not valid JSON, parse throws an error, so it is wise to wrap it in try...catch.
const task = { id: 1, title: 'Study', done: false, tags: ['js'] };
const text = JSON.stringify(task);
console.log(text); // {"id":1,"title":"Study","done":false,"tags":["js"]}
console.log(typeof text); // string
console.log(JSON.stringify(task, null, 2)); // pretty printed
const back = JSON.parse(text);
console.log(back.title); // Study
try {
JSON.parse('{bad json}');
} catch (error) {
console.log('Invalid JSON:', error.name); // SyntaxError
}Arrays of objects: the most common format
In real applications you will almost always work with lists of objects: users, products, messages. The data that arrives from a server has exactly that shape, a JSON array of objects. With what you learned in week 4 you can already filter, transform and total those lists. To group elements by a property, Object.groupBy (available in Node 22 and current browsers) creates an object whose keys are the groups. If you need a dictionary with fast lookup by identifier, Map is an alternative to objects that accepts any type of key and keeps insertion order.
const people = [
{ name: 'Ana', city: 'Lima' },
{ name: 'Leo', city: 'Quito' },
{ name: 'Eva', city: 'Lima' }
];
const byCity = Object.groupBy(people, (p) => p.city);
console.log(byCity.Lima.map((p) => p.name)); // [ 'Ana', 'Eva' ]
const byName = new Map(people.map((p) => [p.name, p]));
console.log(byName.get('Leo').city); // Quito✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов