webroad.online
  1. 1Web
  2. 2HTML
  3. 3CSS
  4. 4JavaScript
  5. 5TypeScript
  6. 6Git
  7. 7Tooling
  8. 8React
  9. 9State management
  10. 10Next.js
  11. 11Forms
  12. 12Data and backend
  13. 13SEO
  14. 14Tailwind CSS
  15. 15Animations
  16. 16Testing
  17. 17Architecture
JavaScript · Lesson 9 of 17

Objects and destructuring

Shorthand, spread, destructuring, Object.entries and groupBy.

Updated

What an object is

An object is a collection of key → value pairs. If an array answers "what's the third element?", an object answers "what's the name? and the age?".

const user = {
  name: 'Ana',          // key: value
  age: 30,
  isAdmin: false,
  address: { city: 'Boston' },          // a value can be another object
  greet() { return `Hello, ${this.name}` },  // or a function (a method)
}

Objects describe one thing with several properties: a user, a product, an order, a component's configuration, React props.

Array or object?

Array Object
Access by position ([0]) by name (.name)
Order matters doesn't matter (in practice)
For lists of similar things describing one thing / a dictionary
Example products product

Most common: an array of objects — a list of products, each product being an object.

Creating — useful syntax

const name = 'Ana'
const field = 'email'

const user = {
  name,                         // shorthand — same as name: name
  [field]: 'ana@x.com',         // computed key — the key = the value of field
  'full-name': 'Ana Smith',     // a key with special characters — in quotes
}

Access — kinds and when

Syntax When Example
obj.key the key is fixed and known user.name
obj[expr] the key is in a variable or has special characters user[field], obj['full-name']
obj?.key the object may be missing user?.address?.city
'key' in obj / Object.hasOwn(obj, 'key') checking whether the key exists different from "has a truthy value"

A missing property → undefined (not an error). You only get an error when you read something from undefined: undefined.city → TypeError. Hence ?..

Destructuring — pulling fields out into variables

const { name, age } = user                       // two variables
const { name: userName } = user                  // renaming
const { role = 'user' } = user                   // a default value
const { address: { city } } = user               // nested
const { password, ...safeUser } = user           // take one key out, keep the rest

Most often in parameters — exactly what a component's props look like:

function Card({ title, children, variant = 'default' }) { ... }

Spread — copying and combining

const updated = { ...user, age: 31 }           // a copy + one changed key
const settings = { ...defaults, ...userPrefs } // the last value for the same key wins

Spread makes a shallow copy — the objects inside stay shared. Details in References and immutability.

Iterating over an object

Method Returns
Object.keys(obj) ['name', 'age']
Object.values(obj) ['Ana', 30]
Object.entries(obj) [['name', 'Ana'], ['age', 30]]
Object.fromEntries(entries) the inverse of entries

The recipe "transform an object like an array":

const prices = { apple: 2, pear: 3 }
const doubled = Object.fromEntries(
  Object.entries(prices).map(([fruit, price]) => [fruit, price * 2]),
)

Grouping

Object.groupBy(products, p => p.category)
// { laptops: [...], accessories: [...] }

An object as a dictionary (lookup)

When you often search by an id, turn the array into an object (or a Map) — the lookup becomes instant:

const byId = Object.fromEntries(users.map(u => [u.id, u]))
byId[42]   // instead of users.find(u => u.id === 42) every time

Summary

  • An object = key → value; it describes one thing.
  • .key for fixed keys, [expr] for dynamic keys, ?. when it may be missing.
  • Destructuring pulls out fields, spread copies and combines.
  • Object.entries + fromEntries for transformations.

Official sources

Exercises

Was this page helpful?

One tap — no account needed.