Unpack complex object using ES6 spread operator-JavaScript

JavaScript ES6 introduces new syntax and excellent features that will make your code more modern and readable. It enables you to write less code and accomplish more. ES6 introduces many new features, including arrow functions, template strings, class destruction, Modules, spread, and many more. {alertInfo}

This post will show you how to unpack a complex javascript object using the ES6 spread operator.
Let’s suppose you have the following javascript object

const person = {
  firstName: "santosh",
  lastName: "singh",
  address: {
    phone: {
      mobile: "99991235",
      countryCode: "60"
    },
    email: "santosh.singh@example.com"
  }
}

and you want to get mobile and countryCode from the object.

const {
    phone: {
      mobile,
      countryCode
    }
  
} = person;
console.log(mobile,countryCode); // 99991235,60

How to rename the property while unpacking the object

Let’s suppose you want to rename the property mobile as mobileNumber while using the spread operator, you can add a new property name using : as below

const {
    phone: {
      mobile:mobileNumber,
      countryCode
    }
  
} = person;

if you try to print mobile property javascript will throw an error that mobile is not defined because we renamed it to mobileNumber

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post