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)
a to arr using const { a : arr } = objconst { a: [...arr] } = obj;, if that's needed. (OP's requirements aren't all that clear, IMO)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)
arr=obj.a....obj.ainto a new object (i.e. shallow copying). Do you intend to get the original array or create a new one?let {a: arr} = {'id': 1, a: [1, 2, 3]}{ a: obj.a }?