LearnFrenzy
Sign in Take a free test

Working with Salesforce Data · Lesson 7 of 25

Objects, Destructuring and Spread in LWC

5 min read Updated Nov 8, 2026 Saurabh Samir

Every record you touch in LWC is a JavaScript object: an Account from Apex, a { data, error } pair from @wire, the detail of a custom event, the state of a form. Three modern features – destructuring, spread and computed keys – make that code short and clear, and they're the backbone of updating state the way LWC expects.

In this lesson

  • Object literal shortcuts
  • Destructuring with defaults, renames and nesting
  • Spread and rest for copying and merging
  • Object.keys, values, entries and fromEntries
  • One change handler for a whole form

Object literal shortcuts

const Name = 'Acme';
const Industry = 'Energy';
const field = 'Rating';

const account = {
    Name,                         // shorthand for Name: Name
    Industry,
    [field]: 'Hot',               // computed key: the property name comes from a variable
    describe() {                  // method shorthand
        return `${this.Name} (${this.Industry})`;
    },
};

console.log(account.Rating, account['Industry'], account.describe());
console.log('Phone' in account, Object.hasOwn(account, 'Name'));

Output

Hot Energy Acme (Energy)
false true

Destructuring

Destructuring pulls properties into variables in one line. You'll write it every day in wire handlers:

// the shape a wired Apex method hands to a wire function
const result = { data: [{ Id: '003A', Name: 'Ravi Kumar', Account: { Name: 'Acme' } }], error: undefined };

const { data, error } = result;
console.log(data.length, error);

// rename, default, nested
const [first] = data;                                     // array destructuring: first element
const { Name: contactName, Title = 'No title', Account: { Name: accountName } } = first;
console.log(contactName, '|', Title, '|', accountName);

// nested destructuring throws if a level is missing – combine with ?. instead
const lead = { Company: 'Globex' };
const ownerName = lead.Owner?.Name ?? 'Unassigned';
console.log(ownerName);

// swap without a temp variable
let a = 'left', b = 'right';
[a, b] = [b, a];
console.log(a, b);

Output

1 undefined
Ravi Kumar | No title | Acme
Unassigned
right left

In a wire function you destructure right in the parameter list:

@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
    if (data) {
        this.contacts = data;
        this.error = undefined;
    } else if (error) {
        this.error = error;
        this.contacts = [];
    }
}

Spread and rest

const defaults = { pageSize: 25, sortBy: 'Name', sortDirection: 'asc' };
const userChoice = { sortBy: 'CreatedDate', sortDirection: 'desc' };

const settings = { ...defaults, ...userChoice };     // later spreads win
console.log(settings);

const record = { Id: '001A', Name: 'Acme', attributes: { type: 'Account' }, Rating: 'Hot' };
const { attributes, Id, ...fields } = record;        // rest: everything except attributes and Id
console.log(fields);

// update one property and get a NEW object (the LWC-friendly way)
const updated = { ...record, Rating: 'Warm' };
console.log(record.Rating, updated.Rating, record === updated);

Output

{ pageSize: 25, sortBy: 'CreatedDate', sortDirection: 'desc' }
{ Name: 'Acme', Rating: 'Hot' }
Hot Warm false

Spread is a shallow copy

{ ...record } copies the top level only. Nested objects such as record.Account are still shared with the original. If you need to change something nested, spread that level too: { ...record, Account: { ...record.Account, Name: 'New' } }.

Object.keys, values and entries

const fieldLabels = { Name: 'Account Name', Industry: 'Industry', AnnualRevenue: 'Annual Revenue' };

console.log(Object.keys(fieldLabels));
console.log(Object.values(fieldLabels).join(' · '));

// entries → change → fromEntries: the standard way to transform an object
const columns = Object.entries(fieldLabels).map(([fieldName, label]) => ({ label, fieldName }));
console.log(columns);

const counts = { Hot: 4, Warm: 0, Cold: 2 };
const nonZero = Object.fromEntries(Object.entries(counts).filter(([, n]) => n > 0));
console.log(nonZero);

Output

[ 'Name', 'Industry', 'AnnualRevenue' ]
Account Name · Industry · Annual Revenue
[
  { label: 'Account Name', fieldName: 'Name' },
  { label: 'Industry', fieldName: 'Industry' },
  { label: 'Annual Revenue', fieldName: 'AnnualRevenue' }
]
{ Hot: 4, Cold: 2 }

The second line of output is a typical datatable columns definition, built from a label map instead of typed out by hand.

One change handler for a whole form

Instead of one handler per input, give each input a name and use a computed key to update a single form object. Spread creates a new object, so LWC re-renders:

<!-- leadForm.html -->
<template>
    <lightning-input label="First name" name="FirstName" value={form.FirstName} onchange={handleChange}></lightning-input>
    <lightning-input label="Company" name="Company" value={form.Company} onchange={handleChange}></lightning-input>
    <lightning-input type="email" label="Email" name="Email" value={form.Email} onchange={handleChange}></lightning-input>
    <p>{preview}</p>
</template>
// leadForm.js
import { LightningElement } from 'lwc';

export default class LeadForm extends LightningElement {
    form = { FirstName: '', Company: '', Email: '' };

    handleChange(event) {
        const { name, value } = event.target;
        this.form = { ...this.form, [name]: value };     // computed key + spread
    }

    get preview() {
        const filled = Object.entries(this.form).filter(([, v]) => v).map(([k]) => k);
        return filled.length ? `Filled: ${filled.join(', ')}` : 'Nothing filled yet';
    }
}

Result

First name [] Company [] Email []
Nothing filled yet

› type “Meera” into First name
First name [Meera] Company [] Email []
Filled: FirstName

› type “Globex” into Company
First name [Meera] Company [Globex] Email []
Filled: FirstName, Company

Add a fourth field and you only add a line of HTML – the JavaScript doesn't change. The form object can go straight to Apex or createRecord as the record's fields.

Practice

Try it yourself

  1. Remove the attributes property from every record in records without changing the originals.

    Show answer

    const clean = records.map(({ attributes, ...rest }) => rest); – destructuring with rest in the callback's parameter.

  2. Why does this.form.Company = value; sometimes fail to update the screen, while this.form = { ...this.form, Company: value }; always works?

    Show answer

    Without @track, LWC only notices when a field is assigned a new value, not when a property inside the object changes. The spread version assigns a new object. More in reactivity and immutable data.

Quick check

How do you rename while destructuring?

const { Name: accountName } = record;

If two spread objects share a key, which value wins?

The later one.

Does spread copy nested objects?

No – it is shallow; nested objects are shared.

Summary

  • Use shorthand and computed keys to build objects concisely.
  • Destructure wire results and records; use ?. for optional nested paths.
  • Spread merges and creates new objects – the reactive way to update state.
  • entries → map/filter → fromEntries transforms objects cleanly.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links