Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

snippet for creating object from destructured array

For example, I had an array with 3 numbers:

var arr = [124, -50, 24];

and I need to convert this array to the object:

{
   x: 124,
   y: -50,
   z: 24
}

I don`t want to use "old-style" syntax for this, for example:

{
  x: arr[0],
  y: arr[1],
  z: arr[2]
}

so for now, I`m using that syntax:

const [x, y, z] = [...arr];
const obj = {x, y, z};

But, is there is any way to do this with a straight dectructuring array to object without need of temporary variables?

like image 213
Vlad Povalii Avatar asked Sep 26 '17 12:09

Vlad Povalii


People also ask

Can an object be Destructured in JavaScript?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.

Can you give an example for Destructuring an object or an array?

In the first line, we are declaring a new variable studentsArr , and assigning it the value of an array of student names. Line 2 is where we destructure. In line 2 we declare three variables; first , second , and third . By declaring them on the left-hand side, we initiate destructuring.

What is the name of the technique used to extract array values into new variables?

Array destructuring is a unique technique that allows you to neatly extract an array's value into new variables.


1 Answers

As it was already mentioned in the comment you can use an Immediately Invoked Function Expression (IIFE) to create the object in a single step, but it's less readable then multiple steps.

const arr = [124, -50, 24];
const obj = (([x, y, z]) => ({ x, y, z }))(arr);

console.log(obj);
like image 113
Ori Drori Avatar answered Nov 03 '22 00:11

Ori Drori