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 ?

6
  • arr=obj.a .... Commented May 16, 2019 at 17:38
  • 2
    use brackets: arr = [...obj.a] Commented May 16, 2019 at 17:39
  • 2
    This isn't destructuring, BTW. It's spreading obj.a into a new object (i.e. shallow copying). Do you intend to get the original array or create a new one? Commented May 16, 2019 at 17:40
  • i think he's trying to do let {a: arr} = {'id': 1, a: [1, 2, 3]} Commented May 16, 2019 at 17:43
  • Or did you mean { a: obj.a } ? Commented May 16, 2019 at 17:54

4 Answers 4

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)

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

3 Comments

You can rename the a to arr using const { a : arr } = obj
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 from "I want to destructure and get the array a from obj", I'm assuming. OP's got destructuring and spread syntax mixed up.
0

Almost - it's the other way round :)

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

Comments

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

Comments

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)

Comments

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.