Javascript ES6 array and object destructuring

Array and Object Destructuring

There are two most used data structures in javascript; array and object. Array and object destructuring is a significant feature in javascript ES6.

ES6 Array Destructuring

Usually, to access an item in an array, you would have to access the items via their indexes as shown below.

const animals = ['๐Ÿ‘', '๐Ÿˆ', '๐Ÿ„', '๐Ÿช', '๐Ÿ–'];
console.log(animals[2])
// ๐Ÿ„
console.log(animals[4])
// ๐Ÿ–

However, you might want to assign the values of an array to separate variables. Destructuring is a clean and simple way of achieving that. With destructuring, there is no need to use indexes or loops.

Now, using destructuring in the example above, we can assign the values of the array to variables as shown in the example below:

const animals = ['๐Ÿ‘', '๐Ÿˆ', '๐Ÿ„', '๐Ÿช', '๐Ÿ–'];
const [sheep, cat, cow, cammel, pig] = animals;
console.log(sheep)
// ๐Ÿ‘
console.log(cat)
// ๐Ÿˆ
console.log(cow)
// ๐Ÿ„
console.log(cammel)
// ๐Ÿช
console.log(pig)
// ๐Ÿ–

In the same way, you can assign default values to the variables. Thus, if you have more variables than there are in the array, your variables will still have values defined.

const fruits = ['๐Ÿ’','๐Ÿ‡','๐ŸŽ','๐Ÿ'];
const [
   cherries = 'Two Cherries',
   grapes = 'A lot of Grapes',
   apple = 'Red Apple',
   pear = 'One Pear',
   peach = '๐Ÿ‘',
   mango = '๐Ÿฅญ'
] = fruits;
console.log(grapes)
// ๐Ÿ‡
console.log(pear)
// ๐Ÿ
console.log(peach)
// ๐Ÿ‘
console.log(mango)
// ๐Ÿฅญ

We can assign value to a declared variable using destructuring.

let pie, cupcake;
[pie, cupcake] = ['๐Ÿฅง', '๐Ÿง']
console.log(pie)
// ๐Ÿฅง
console.log(cupcake)
// ๐Ÿง

Variable Swap

Again, we can swap two variables in a single destructuring expression.

let owl = '๐Ÿฆข';
let swan = '๐Ÿฆ‰';
[owl, swan] = [swan, owl]
console.log(owl)
// ๐Ÿฆ‰
console.log(swan)
// ๐Ÿฆข

Using rest

However, trailing items in an array can be captured with a “rest” pattern

let [peacock, parrot, ...restBirds] = ["๐Ÿฆš", "๐Ÿฆœ", "๐Ÿฆข", "๐Ÿฆฉ", "๐Ÿฆ", "๐Ÿง", "๐Ÿฆ…", "๐Ÿฆ†", "๐Ÿฆ‰"];
console.log(peacock)
// ๐Ÿฆš
console.log(parrot)
// ๐Ÿฆœ
console.log(restBirds)
// ["๐Ÿฆข", "๐Ÿฆฉ", "๐Ÿฆ", "๐Ÿง", "๐Ÿฆ…", "๐Ÿฆ†", "๐Ÿฆ‰"]

Moreover, items in the array being destructured can be skipped.

// skipping ๐Ÿฆข, ๐Ÿฆฉ, ๐Ÿฆ
let [peacock, parrot, ,,, ...restBirds] = ["๐Ÿฆš", "๐Ÿฆœ", "๐Ÿฆข", "๐Ÿฆฉ", "๐Ÿฆ", "๐Ÿง", "๐Ÿฆ…", "๐Ÿฆ†", "๐Ÿฆ‰"];
console.log(peacock)
// ๐Ÿฆš
console.log(parrot)
// ๐Ÿฆœ
console.log(restBirds)
// ["๐Ÿง", "๐Ÿฆ…", "๐Ÿฆ†", "๐Ÿฆ‰"]

Array returned from a function

Furthermore, destructuring can make working with an array returned from a function more simpler.

function mamals() {
  return ["๐Ÿฆ™", "๐Ÿฆฆ", "๐Ÿฆง", "๐Ÿฆ˜"]
}
let [llama, otter, orangutan, kangaroo] = mamals()
console.log(llama)
// ๐Ÿฆ™
console.log(otter)
// ๐Ÿฆฆ
console.log(orangutan)
// ๐Ÿฆง
console.log(kangaroo)
// ๐Ÿฆ˜
function fruits() {
  return ["๐Ÿ", "๐Ÿฅญ", "๐Ÿ‘", "๐Ÿ’"]
}
// skipping ๐Ÿฅญ and ๐Ÿ‘
let [pear,,,cherries] = fruits()
console.log(pear)
// ๐Ÿ
console.log(cherries)
// ๐Ÿ’

Object Destructuring

With ES6, we can use destructuring to assign object values to variables.

Basic Object Destructuring

The example below uses the same variables as the keys in the object but you can use a different variable name as well.

const vehicles = {
  car: "๐Ÿš—",
  taxi: "๐Ÿš•",
  bus: "๐ŸšŒ",
  minibus: "๐Ÿš"
};
const { car, taxi, bus, minibus } = vehicles
console.log(car)
// ๐Ÿš—
console.log(taxi)
// ๐Ÿš•
console.log(bus)
// ๐ŸšŒ
console.log(minibus)
// ๐Ÿš

Variable assignment without declaration

let boy, girl;
({boy, girl} = {boy: "๐Ÿ‘ฆ", girl: "๐Ÿ‘ง"})

You probably have noticed the ( … ) around the object literal destructuring assignment without a declaration. This is because the parentheses ( … ) around the assignment statement are required.

let boy, girl;
{boy, girl} = {boy: "๐Ÿ‘ฆ", girl: "๐Ÿ‘ง"} 
//invalid stand-alone syntax as {boy, girl} is considered a block and not an object literal.
const {boy, girl} = {boy: "๐Ÿ‘ฆ", girl: "๐Ÿ‘ง"} 
// is a valid syntax
({boy, girl} = {boy: "๐Ÿ‘ฆ", girl: "๐Ÿ‘ง"}) // is also a valid statement

Default Values

Default values can be assigned to the variable in a destructuring assignment if the unpacked value from the object is undefined.

const {unicorn = "๐Ÿฆ†", eagle = "๐Ÿฆ…", chicken = "๐Ÿ”"} = {unicorn: "๐Ÿฆ„"}
console.log(unicorn)
// ๐Ÿฆ„
console.log(chicken)
// ๐Ÿ”

Likewise, a property unpacked from an object can be assigned to a variable with a different name.

const balls = {fball: "โšฝ๏ธ", bball: "๐Ÿ€", sball: "๐ŸฅŽ", vball: "๐Ÿ"}
const {fball: football, bball: basketball, sball: softball, vball: volleyball} = balls
console.log(football)
// โšฝ๏ธ
console.log(basketball)
// ๐Ÿ€
console.log(softball)
// ๐ŸฅŽ
console.log(volleyball)
// ๐Ÿ

Similarly, we can unpack fields from objects passed as a function parameter

const animals = {
  id: 23,
  location: "Madagascar",
  birds: {
    swan: "๐Ÿฆข",
    cockerel: "๐Ÿ“",
    turkey: "๐Ÿฆƒ",
    flamingo: "๐Ÿฆฉ",
    parrot: "๐Ÿฆœ"
  },
  mammals: {
    skunk: "๐Ÿฆจ",
    raccoon: "๐Ÿฆ",
    kangaroo: "๐Ÿฆ˜",
    badger: "๐Ÿฆก",
    llama: "๐Ÿฆ™"
  }
}
function whereis({location, mammals: {raccoon: image}}){
  return `${image} is located at ${location}`
}
function whichGroup({birds: {swan: bird}, mammals: {badger: mammal}}){
  return `${bird} is a bird and ${mammal} is a mamal`
}
console.log(whereis(animals))
console.log(whichGroup(animals))

Nested object and array destructuring

We can also destructure a nested object and array.

const animals = {
  id: 23,
  location: "Madagascar",
  birds: [
    {
      swan: "๐Ÿฆข",
      family: "Anatidae",
      genus: "Cygnus"
    }
  ],
  mammals: {
    skunk: "๐Ÿฆจ",
    raccoon: "๐Ÿฆ",
    kangaroo: "๐Ÿฆ˜",
    badger: "๐Ÿฆก",
    llama: "๐Ÿฆ™"
  }
}
let {
  location: animalLocation,
  birds: [
    {
      swan: emoji,
      family: animalFamily,
      genus: animalGenus
    }
  ]
} = animals
console.log(animalLocation)
//Madagascar
console.log(emoji)
// ๐Ÿฆข
console.log(animalFamily)
// Anatidae
console.log(animalGenus)
// Cygnus

Rest in Object Destructuring

Of course, it is possible to use rest in object destructuring. In this case, the rest syntax can be used to collect remaining property keys that are not already picked off by the destructuring pattern.

const flags = { colombia: "๐Ÿ‡จ๐Ÿ‡ด", china: "๐Ÿ‡จ๐Ÿ‡ณ", cyprus: "๐Ÿ‡จ๐Ÿ‡พ", ecuador: "๐Ÿ‡ช๐Ÿ‡จ", egypt: "๐Ÿ‡ช๐Ÿ‡ฌ", france: "๐Ÿ‡ซ๐Ÿ‡ท"}
let {colombia, china, ...restCountries} = flags
console.log(colombia)
// ๐Ÿ‡จ๐Ÿ‡ด
console.log(china)
// ๐Ÿ‡จ๐Ÿ‡ณ
console.log(restCountries)
// { cyprus: "๐Ÿ‡จ๐Ÿ‡พ", ecuador: "๐Ÿ‡ช๐Ÿ‡จ", egypt: "๐Ÿ‡ช๐Ÿ‡ฌ", france: "๐Ÿ‡ซ๐Ÿ‡ท"}

Finally, With ES6 array and object destructuring, you can do a whole lot. And I believe there is so much to destructuring, so I will appreciate it if you can share in the comment your experience with ES6 destructuring.

Useful Resources

Destructuring assignment
Destructuring assignment – JavaScript | MDN
ES6 In Depth: Destructuring – Mozilla Hacks – the Web developer blog

One response to “Javascript ES6 Array and Object Destructuring”

  1. […] Destructuring assignment will not only save a lot of time makes your code cleaner and simpler. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Attach images – Only PNG, JPG, JPEG and GIF are supported.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Quote of the week

"People ask me what I do in the winter when there's no baseball. I'll tell you what I do. I stare out the window and wait for spring."

~ Rogers Hornsby

All rights resolved