Skip to content

Destructuring array of objects

  • by

Destructuring array of objects allow to manipulate and switch elements you unpacked depending on the type of operation you want to perform.

Destructure nested objects

let arr = [
  {val:"a"},
  {val:"b"}
];

const [{val: valueOfA}, {val: valueOfB}] = arr

The destructuring array of objects

Simple example code how to do destructuring.

<!DOCTYPE html>
<html>
<body>
  <script>
   const someArray = [
   { data: 100 },
   { data: 200 },
   { data: 300 }
   ];

   const [
   { data: array0 },
   { data: array1 },
   { data: array2 }
   ] = someArray

   console.log(array0, array1, array2);

 </script>
</body>
</html>

Output:

Destructuring array of objects

What is happening is that you’re first extracting each object from someArray then destructuring each object by extracting the data property and renaming it:

// these 2 destructuring steps
const [ obj1, obj2, obj3 ] = someArray // step 1
const { data: array0 } = obj1 // step 2
const { data: array1 } = obj2 // step 2
const { data: array2 } = obj3 // step 2

// written together give
const [
  { data: array0 },
  { data: array1 },
  { data: array2 }
] = someArray

Maybe combine destructuring with mapping for (potentially) more readable code:

const [array0, array1, array2] = someArray.map(item => item.data)

Example

const someArray = [
  { data: 1 },
  { data: 2 },
  { data: 3 }
];

const [array0, array1, array2] = someArray.map(item => item.data)

console.log(array0, array1, array2);

Source: https://stackoverflow.com/questions/49413544

How to destructure an array of objects into multiple arrays of its keys?

Answer:

const arr = [
  { id: 1, name: 'Foo'}, 
  { id: 2, name: 'Bar'}, 
  { id: 3, name: 'FooBar'}, 
  { id: 4, name: 'BarFoo'}
]

const {ids, names} = {ids: arr.map(a => a.id), names: arr.map(a => a.name)}

console.log(ids)
console.log(names)

Output:

[
  1,
  2,
  3,
  4
]
[
  "Foo",
  "Bar",
  "FooBar",
  "BarFoo"
]

Do comment if you have any doubts or suggestions on this Js array object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading