DEV Community

Amit Chauhan
Amit Chauhan

Posted on

Safely access nested object with ES6 Destructuring

How can we use ES6 Destructuring to access values from nested object or array without using safeguards with && operators?

Let's start with a basic example of destructuring. This is how we can destructure values from the object and assign them to variables.
We can also rename variables to a different name and give default value ie. if an object doesn't have that key(this is important for our topic)

  const data = {
    id: '123',
    value: 'someValue'
  };

  // access id and value from data with destructuring 
  const { id , value } = data;
Enter fullscreen mode Exit fullscreen mode

Now let's try to access the nested object.

  const data = {
    user: {
      id: 1,
      name: {
        first: 'Amit',
        last: 'Chauhan'
      }
    }
  };
Enter fullscreen mode Exit fullscreen mode

If we want to safely read firstName from this data this is how we would write without destructuring

  const firstName = data && data.user && data.user.name && data.user.name.first;
Enter fullscreen mode Exit fullscreen mode

Let's do it with destructuring.

  const {
    user: {
      name: {
        first: firstName // rename variable to firstName
      } = {} // this part is where we give default value to empty object so code doesn't break
    } = {} 
  } = data;
  console.log(firstName); // Amit
Enter fullscreen mode Exit fullscreen mode

We can use destructuring to access an array as well.

  const dataArray = [{
    name: {
      first: 'Amit'
    }
  }];

  const [{
    name: {
      first: firstName
    } = {}
  } = {}] = dataArray;
  console.log(firstName); // Amit
Enter fullscreen mode Exit fullscreen mode

Bonus tip

We can use destructuring to swap variables.

let a = 10;
let b = 20;

[a, b] = [b, a];
console.log({ a, b }); // { a: 20, b: 10 }
Enter fullscreen mode Exit fullscreen mode

Discussion (0)