惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
L
LINUX DO - 最新话题
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
Know Your Adversary
Know Your Adversary
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
The Last Watchdog
The Last Watchdog
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
WordPress大学
WordPress大学
L
LINUX DO - 热门话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Visual Studio Blog
O
OpenAI News
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
Spread Privacy
Spread Privacy
Y
Y Combinator Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
T
The Blog of Author Tim Ferriss
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
N
News and Events Feed by Topic
Project Zero
Project Zero
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
G
Google Developers Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Use Object Destructuring in JavaScript
Dmitri Pavlutin · 2020-05-10 · via Dmitri Pavlutin Blog

Object destructuring is a useful JavaScript feature to extract properties from objects and bind them to variables.

Even better, object destructuring can extract multiple properties in a single statement, can access properties from nested objects, and can set a default value if the property doesn't exist.

This post will help you understand how to use object destructuring in JavaScript.

Table of Contents

  • 1. The need for object destructuring
  • 2. Extracting a property
  • 3. Extracting multiple properties
  • 4. Default values
  • 5. Aliases
  • 6. Extracting properties from nested objects
  • 7. Extracting a dynamic name property
  • 8. Rest object after destructuring
  • 9. Common use cases
    • 9.1 Bind properties to variables
    • 9.2 Function parameter destructuring
  • 10. Summary

1. The need for object destructuring

Imagine you'd like to extract some properties of an object. In a pre-ES2015 environment, you'd need to write the following code:


var hero = {

name: 'Batman',

realName: 'Bruce Wayne'

};

var name = hero.name;

var realName = hero.realName;

console.log(name); // => 'Batman',

console.log(realName); // => 'Bruce Wayne'


Open the demo.

The property hero.name value is assigned to the variable name. Same way hero.realName value is assigned to realName.

By writing var name = hero.name, you have to mention the name binding 2 times, and the same for realName. This way of accessing properties and assigning them to variables requires boilerplate code.

That's where the object destructuring syntax is useful: you can read a property and assign its value to a variable without duplicating the property name. What is more, you can read multiple properties from the same object in just one statement!

Let's refactor the above script and apply the object destructuring to access the properties name and realName:


const hero = {

name: 'Batman',

realName: 'Bruce Wayne'

};

const { name, realName } = hero;

console.log(name); // => 'Batman',

console.log(realName); // => 'Bruce Wayne'


Open the demo.

const { name, realName } = hero is an object destructuring assignment. This statement defines the variables name and realName, then assigns to them the values of properties hero.name and hero.realName correspondingly.

Compare two approaches to accessing the object properties:


const name = hero.name;

const realName = hero.realName;

// is equivalent to:

const { name, realName } = hero;


it's visible that object destructuring is handier because neither the property names nor the object variable is duplicated.

JavaScript Object Destructuring Inforgraphic

The syntax of object destructuring is pretty simple:


const { identifier } = expression;


Where identifier is the name of the property to access and expression should evaluate to an object. After the destructuring, the variable identifier contains the property value.

Here's the equivalent code using a property accessor:


const identifier = expression.identifier;


Let's try object destructuring in practice:


const hero = {

name: 'Batman',

realName: 'Bruce Wayne'

};

const { name } = hero;

console.log(name); // => 'Batman'


Open the demo.

The statement const { name } = hero defines the variable name and initializes it with the value of hero.name property.

To destructure the object into multiple properties, enumerate as many properties as you like adding commas , in-between:


const { identifier1, identifier2, ..., identifierN } = expression;


Where identifier1, ..., identifierN are names of properties to access, and expression should evaluate to an object. After the destructuring, the variables identifier1, ..., identifierN contain corresponding properties values.

Here's the equivalent code:


const identifier1 = expression.identifier1;

const identifier2 = expression.identifier2;

// ...

const identifierN = expression.identifierN;


Let's take a look again at the example from the first section, where 2 properties are extracted:


const hero = {

name: 'Batman',

realName: 'Bruce Wayne'

};

const { name, realName } = hero;

console.log(name); // => 'Batman',

console.log(realName); // => 'Bruce Wayne'


Open the demo.

const { name, realName } = hero creates 2 variables name and realName assigned with values of corresponding properties hero.name and hero.realName.

4. Default values

If the destructured object doesn't have the property specified in the destructuring assignment, then the variable is assigned with undefined. Let's see how it happens:


const hero = {

name: 'Batman',

realName: 'Bruce Wayne'

};

const { enemies } = hero;

console.log(enemies); // => undefined


Open the demo.

After destructuring the variable enemies is undefined because the property enemies doesn't exist in the object hero.

Fortunately, you can set a default value if the property doesn't exist in the destructured object:


const { identifier = defaultValue } = expression;


Where identifier is the name of the property to access and expression should evaluate to an object. After destructuring, the variable identifier contains the property value or is assigned with defaultValue if the property identifier doesn't exist.

Here's the equivalent code:


const identifier = expression.identifier === undefined ?

defaultValue : expression.identifier;


Let's change the previous code sample, and use the default value feature:


const hero = {

name: 'Batman',

realName: 'Bruce Wayne'

};

const { enemies = ['Joker'] } = hero;

console.log(enemies); // => ['Joker']


Open the demo.

Now, instead of being undefined, the variable enemies defaults to ['Joker'].

5. Aliases

To create variables of different names than the properties you can use the aliasing feature of object destructuring.


const { identifier: aliasIdentifier } = expression;


identifier is the name of the property to access, aliasIdentifier is the variable name, and expression should evaluate to an object. After destructuring, the variable aliasIdentifier contains the property value.

The equivalent code:


const aliasIdentifier = expression.identifier;


Here's an example of an object destructuring alias feature:


const hero = {

name: 'Batman',

realName: 'Bruce Wayne'

};

const { realName: secretName } = hero;

console.log(secretName); // => 'Bruce Wayne'


Open the demo.

Looking at const { realName: secretName } = hero, the destructuring defines a new variable secretName (alias variable) and assigns to it the value of hero.realName.

In the previous examples, the objects were plain: the properties have primitive data types (e.g. strings).

But objects can be nested in other objects. In other words, some properties can contain objects.

In such a case, you still can use the object destructuring and access properties from deep. Here's the basic syntax:


const { nestedObjectProp: { identifier } } = expression;


nestedObjectProp is the name of the property that holds a nested object. identifier is the property name to access from the nested object. expression should evaluate to the destructured object.

After destructuring, the variable identifier contains the property value of the nested object.

The above syntax is equivalent to:


const identifier = expression.nestedObjectProp.identifier;


The level of nesting to extract properties from is unlimited. If you want to extract properties from deep, just add more nested curly braces:


const { propA: { propB: { propC: { .... } } } } = object;


For example, the object hero contains a nested object { city: 'Gotham'}.


const hero = {

name: 'Batman',

realName: 'Bruce Wayne',

address: {

city: 'Gotham'

}

};

// Object destructuring:

const { address: { city } } = hero;

console.log(city); // => 'Gotham'


Open the demo.

The object destructuring const { address: { city } } = hero accesses the property city from the nested object and creates a variable city having the property value.

You can extract into variables properties with a dynamic name (the property name is known at runtime):


const { [propName]: identifier } = expression;


propName expression should evaluate to a property name (usually a string), and the identifier should indicate the variable name created after destructuring. expression should evaluate to the object you'd like to destructure.

An equivalent code without object destructuring:


const identifier = expression[propName];


Let's look at an example where prop holds the property name:


const hero = {

name: 'Batman',

realName: 'Bruce Wayne'

};

const prop = 'name';

const { [prop]: name } = hero;

console.log(name); // => 'Batman'


Open the demo.

const { [prop]: name } = hero is an object destructuring that assigns to variable name the value hero[prop], where prop is a variable holding the property name.

8. Rest object after destructuring

The rest syntax is useful to collect the remaining properties after destructuring:


const { identifier, ...rest } = expression;


Where identifier is the name of the property to access and expression should evaluate to an object. After destructuring, the variable identifier contains the property value. rest variable is a plain object with the remaining properties.

For example, let's extract the property name, but collect the rest of the properties into a variable rest:


const hero = {

name: 'Batman',

realName: 'Bruce Wayne',

company: 'WayneCorp'

};

const { name, ...rest } = hero;

console.log(rest); // => { realName: 'Bruce Wayne', company: 'WayneCorp' }


Open the demo.

The destructuring const { name, ...realHero } = hero extracts the property name. Also, the remaining properties (realName and company) are collected into rest.

9. Common use cases

9.1 Bind properties to variables

As seen in many examples before, the object destructuring binds property values to variables.

The object destructuring can assign values to variables declared using const, let, and var. Or even assign to an already existing variable.

For example, here's how to destructure using let statement:


// let

const hero = {

name: 'Batman',

};

let { name } = hero;

console.log(name); // => 'Batman'


Open the demo.

How to destructure using var statement:


// var

const hero = {

name: 'Batman',

};

var { name } = hero;

console.log(name); // => 'Batman'


Open the demo.

And how to destructure to an already declared variable:


// existing variable

let name;

const hero = {

name: 'Batman',

};

({ name } = hero);

console.log(name); // => 'Batman'


Open the demo.

I find it satisfying to combine for..of cycle with object destructuring to extract the property right away:


const heroes = [

{ name: 'Batman' },

{ name: 'Joker' }

];

for (const { name } of heroes) {

console.log(name); // logs 'Batman', 'Joker'

}


Open the demo.

9.2 Function parameter destructuring

Object destructuring can be placed anywhere where an assignment happens.

For example, you could destruct an object right inside the parameter of a function:


const heroes = [

{ name: 'Batman' },

{ name: 'Joker' }

];

const names = heroes.map(

function({ name }) {

return name;

}

);

console.log(names); // => ['Batman', 'Joker']


Open the demo.

function({ name }) destructures the function parameter and creates a variable name holding the value of name property.

10. Summary

Object destructuring is a powerful feature to extract properties from an object and bind these values to variables.

I like object destructuring due to the concise syntax and the ability to extract multiple variables in one statement.

Have questions regarding object destructuring? Ask in a comment below!