11

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?

13
  • 4
    off the top of my head var obj = (([x,y,z]) => ({x,y,z}))(arr); Commented Sep 26, 2017 at 12:35
  • stackoverflow.com/q/45971203/1048572? Commented Sep 26, 2017 at 12:36
  • 2
    I think this is similar: stackoverflow.com/questions/38242744/… Commented Sep 26, 2017 at 12:39
  • 1
    @JaromandaX: simidentical? identilar? Commented Sep 26, 2017 at 12:45
  • 1
    It remains only to understand what is going on there @VladPovalii it's an IIFE of the arrow function ([x,y,z]) => ({x,y,z}). But imo you should store this function const arr2point = ([x,y,z]) => ({x,y,z}); and use that const obj = arr2point(arr) instead of using the IIFE inline. Commented Sep 26, 2017 at 12:51

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

lol. I've changed the sorting order by mistake, and this question popped. I've answered it like it was new (not really looked at the comments), and totally forgot about it.
:) Anyway its ok..finally this question will have the right answer, so thanks!
1

You can also do

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

to avoid the temporary variables, but I'd question whether that's an improvement.

Comments

1

Just use this

let obj = {...arr}

1 Comment

Not quite right, because you want to control the object keys naming ("x", "y", "z") - but after this keys will be: "0", "1", "2"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.