HomeTutorsContact

How to extract deeply nested property in JavaScript(ES6)?

By Gulshan Saini
Published in JavaScript
June 29, 2020
1 min read

Accessing nested object properties in JavaScript used to be a huge pain using the dot notation. However, things got easier in ES6 with the introduction of destructuring assignments.

Let’s say we have the following complex object and we want to get the value of property company that is under the ad property. The old way of doing this is to use the dot notation data.ad.company

const data = {
  page: 2,
  per_page: 6,
  total: 12,
  total_pages: 2,
  data: [
    {
      id: 7,
      email: 'gulshan.saini@xyz.mail',
      first_name: 'Gulshan',
      last_name: 'Saini'
    }
  ],
  ad: {
    company: 'Tutorials Tips',
    url: 'http://tutorials.tips/'
  }
}

In ES6 there is a better and simpler way of extracting the nested objects. To extract the value of company we could simply write

let {
  ad: { company }
} = data

Next, we can just log the value to see the result

console.log(company) // "Tutorials Tips"

We could even rename(alias) the company property to organization while destructuring as follows

let {
  ad: { company: organization }
} = data

That’s where ES6 destructuring gets more powerful.


Tags

#javascript
Previous Article
How to delete a property from a JavaScript object?

Related Posts

JavaScript
How to check if a string contains a substring in JavaScript?
January 05, 2021
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Angular
JavaScript
ReactJS
Typescript

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media