0

I have an object like this:

obj = {'id': 1, a: [1, 2, 3]}

I want to destructure and get the array a from obj

arr = {...obj.a}

I get:

{0: 1, 1: 2, 2: 3}

which is not an array

How to get the array itself ?

moctarjallo
  • 1,479
  • 1
  • 16
  • 33

4 Answers4

4

You are spreading an array inside {}. This creates an object with indices of the array as keys. This is why you get {0: 1, 1: 2, 2: 3}

const a = [ 1, 2 ]

console.log({ ...a })

If you want to get a property into a variable, this is the correct syntax:

const { propertyName } = yourObject
// if you want to have a variable name which is different than the propertyName
const { propertyName: someOtherVariable } = yourObject

Here's the working snippet:

const obj = {'id': 1, a: [1, 2, 3] }

const { a: arr } = obj; // this is same as: const arr = obj.a

console.log(arr)
Moritz Roessler
  • 8,542
  • 26
  • 51
adiga
  • 34,372
  • 9
  • 61
  • 83
  • You can rename the `a` to `arr` using `const { a : arr } = obj` – Moritz Roessler May 16 '19 at 17:45
  • You could create a shallow copy *and* destructure all at once: `const { a: [...arr] } = obj;`, if that's needed. (OP's requirements aren't all that clear, IMO) – p.s.w.g May 16 '19 at 17:47
  • @p.s.w.g from "*I want to destructure and get the array a from obj*", I'm assuming. OP's got destructuring and spread syntax mixed up. – adiga May 16 '19 at 17:56
0

Almost - it's the other way round :)

let {a: arr} = {'id': 1, a: [1, 2, 3]}

Moritz Roessler
  • 8,542
  • 26
  • 51
0

You could destructure to an array by assigning the array to an array with a rest syntax.

var obj = { id: 1, a: [1, 2, 3] },
    [...arr] = obj.a;

console.log(arr);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Use brackets instead of curly braces to spread it into a new array:

const obj = {'id': 1, a: [1, 2, 3]}    
const arr = [...obj.a]
console.log(arr)
Michael Kantz
  • 107
  • 2
  • 10