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;
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.
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.
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.
Object destructuring is new syntax introduced in ES6. It helps create variables by extracting the object's properties in a much simpler way.
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);
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 map
ping with destructuring:
const [array0, array1, array2] = someArray.map(x => x.data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With