Object Destructuring (Javascript)

Object destructuring in Javascript allows you to create constants from items within an object.

How

const initialObject = {
  first: 123,
  second: ['yeah', 'no'],
  third: {
    thing: 1,
    another: 2
  }
};

console.log(initialObject.first) // 123
console.log(initialObject.second[0]) // 'yeah

Basic

const { first, second, third } = initialObject;

console.log(first) // 123
console.log(second[0]) // 'yeah'

Custom Names

const { first: tom, second: cruise, third: hello } = initialObject;

console.log(tom) // 123
console.log(cruise[0]) // 'yeah'

References

Last modified: 202108102210