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 ?
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 ?
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)
Almost - it's the other way round :)
let {a: arr} = {'id': 1, a: [1, 2, 3]}
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);
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)