Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring array of objects in es6

Tags:

In es6, how can i simplify the following lines using destructuring?:

const array0 = someArray[0].data; const array1 = someArray[1].data; const array2 = someArray[2].data; 
like image 408
ssss Avatar asked Mar 21 '18 17:03

ssss


People also ask

Can you Destructure array of objects?

Array DestructuringValues in arrays are destructured based on their index . The variable can be named anything you want, but the variable name associated with the index is how it is assigned. We can also assign values to variables that are already declared.

Is array Destructuring ES6?

Destructuring means to break down a complex structure into simpler parts. With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.

How do you Destructure an array in JavaScript?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

What is object Destructuring in ES6?

Object destructuring is new syntax introduced in ES6. It helps create variables by extracting the object's properties in a much simpler way.


Video Answer


2 Answers

Whether using destructuring would actually be a simplification is debatable but this is how it can be done:

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

Live Example:

const someArray = [    { data: 1 },    { data: 2 },    { data: 3 }  ];    const [    { data: array0 },    { data: array1 },    { data: array2 }  ] = someArray    console.log(array0, array1, array2);

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) 

Live Example:

const someArray = [    { data: 1 },    { data: 2 },    { data: 3 }  ];    const [array0, array1, array2] = someArray.map(item => item.data)    console.log(array0, array1, array2);
like image 167
nem035 Avatar answered Sep 21 '22 06:09

nem035


I believe what you actually want is

const array = someArray.map(x => x.data) 

If you really want three variables (Hint: you shouldn't), you can combine that mapping with destructuring:

const [array0, array1, array2] = someArray.map(x => x.data) 
like image 20
Bergi Avatar answered Sep 21 '22 06:09

Bergi