DEV Community

Cover image for Destructuring nested object
Ahmed Yagoub
Ahmed Yagoub

Posted on

Destructuring nested object

Introduction

Sometimes, we might run into situations where we need to get multiple properties from an object. You might have a function that accepts a nested object as a parameter. For example, the express (backend) functions that accept the request as the first parameter. We need to access multiple properties from the object to use in the function.

Example

Here is an example of a nested object.

const obj = {
  data: {
    day: {
      index: 1
    },
    week: {
      index: 1
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

If we want to get both the index of day and index of week, we could do something like this

    const weekIndex = obj.data.week.weekIndex;
    const dayIndex = obj.data.day.dayIndex;
Enter fullscreen mode Exit fullscreen mode

But with object destructuring, it will be like so

    const {
      data: {
        week: { index: weekIndex },
        day: { index: dayIndex },
      },
    } = obj;
Enter fullscreen mode Exit fullscreen mode

Here, we are destructuring the data from obj, then we are destructuring week and day from data, then destructure each of them to get the index and finally assigning each index to the variable we aim to use in the project.

It might be a few extra lines of code than if we access the object trough dot notation as above. However, it is more visual that we can see the structure of the object which makes it easier to read. As well as we avoid repetition.

Top comments (0)