1

I think I understand destructuring in ES6 well enough. Example:

const obj = {
  foo: 'String1',
  bar: 'String2'
}

let { foo, bar } = obj

console.log(foo) //Prints "String1"

Simple enough.

However, I have a large object with a dynamic number of properties with dynamic names. I'd like to be able to assign them automatically.

Example object:

const obj = {
    a: 'String1',
    b: 'String2',
    c: 'String3',
    // ....
    y: 'String25',
    z: 'String26',
} 

Instead of declaring each variable individually, I tried:

// Instead of 
// { a, b, c, d, so_on, y, z } = obj 
// I try: 

let { ...obj } = obj

But get this error: Identifier 'obj' has already been declared

What's a better way to approach this?

user3183717
  • 4,427
  • 6
  • 20
  • 42
  • 3
    Personally if it is not a hard coded set of variables, seems like a bad idea to do what you want to do. – epascarello Aug 31 '20 at 21:40
  • > let { ...obj } = obj This line doesn't make sense. If I were to decide, I'd just leave the object as-is. MUCH more readable. – paroxyzm Aug 31 '20 at 21:41
  • 1
    What is the actual reason for wanting to do this? How would a bunch of dynamic variables actually help? What is the real problem you are trying to solve by wanting to do this? – epascarello Aug 31 '20 at 21:44

1 Answers1

0

As long as the identifier is different than that of the object you're trying to destructure it should work exactly as you intend it to.

const obj = {
    a: 'String1',
    b: 'String2',
    c: 'String3',
    // ...
    y: 'String25',
    z: 'String26',
} 

const { a, b, ...rest } = obj
// const a: 'String1'
// const b: 'String2'
// const rest: {
//     c: string;
//     ...
//     y: string;
//     z: string;
// }

See this example in the playground.

Aron
  • 8,696
  • 6
  • 33
  • 59