Member-only story

Javascript Object Destructing cheat sheet

Vinodh Thangavel
1 min readJun 23, 2023

--

Destructing is provides us a convenient way of accessing properties and elements of the object and array respectively

Object Structure

Basic Destructing

const {firstName, city} = user;Get firstName and city from user

Rename after destructing

const {city:location} = user;Get city but rename it as location

Default value

const {isActive = true} = user;Default value while destructing

Destructure nested objects

const {education : {school, college} } = user;Destructure nested objects

Pluck required properties and Form new object with the rest

const {firstName, lastName, ...others } = user;Get required properties and create a new object with rest of them

Access value from computed values

//accessing from the computed property,
const prefix1 = 'first'
const prefix2 = 'last'
const suffix ='Name'

const {[prefix1+suffix]:value1,[prefix2+suffix]:value2}=user;
//value1 will have value of firstName , value2 will have value lastName

Assign to already declared values

So far we are declaring the variable with const and destructing in the same statement, if you want to assign a destructured value to already declared variable, we have to wrap with a bracket

let firstName;

({ firstName } = user);
console.log(firstName); // Vinodh

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet