0

this should be pretty easy, but I can't seem to get the syntax right.

    var newObject = {a:1,b:2,c:"three"};
    var {...newObject} = newObject;
    console.log(a); // returns undefined

I'm trying to automatically destructure my objects. I can get it to work if I use

var {a,b,c} = newObject

but I have some long arrays and want to not have to type out all my variables

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Peter Breen
  • 447
  • 1
  • 10
  • 24
  • 6
    Not possible like that - you're basically looking for dynamic variable names, which are terrible and only possible with bad hacks like `eval` – CertainPerformance Oct 26 '18 at 15:36
  • 2
    Why do you need too many variables? Use a loop instead. – Ele Oct 26 '18 at 15:36
  • 4
    What's wrong with directly accessing the object value with `newObject.a`? – slider Oct 26 '18 at 15:39
  • I'm using the variables in a way that doesn't lend itself to looping (I'm not doinig the same thing with every variable). I can definitely access the object value's directly and that's what I'm doing now, it just seems inefficient to keep writing newObject over and over again, so it still seems useful (but certainly not necessary) to do what I'm trying to do. – Peter Breen Oct 26 '18 at 15:49
  • Well if you are accessing it, so why can you not just list them out? Makes sense instead of making tons of unused variables if it would work the way you wanted it too. – epascarello Oct 26 '18 at 15:55
  • 1
    If you uglify your code in the end, `newObject` will be minified nevertheless. Just to mention, but totally not recommended is the with-do statement — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with – Matthi Oct 26 '18 at 15:56
  • @Matthi Sometimes `with` is useful, it's used a lot in templating frameworks. If there's a block of code that will only work with properties of `newObject` it might be worth a look – Dexygen Oct 26 '18 at 16:01
  • I guess for this project, I'm more concerned with efficiency in the writing and readability of the code than performance on the front-end, so having a few extra variables floating around seems fine to me. Thanks all for the ideas about whether this is actually a good idea to try to do (I still haven't seen a good concise way to accomplish this) – Peter Breen Oct 26 '18 at 16:07
  • If you're using so many variables in a scope that you would prefer not to type all their names out, then you're probably going in the wrong direction. – Patrick Roberts Oct 26 '18 at 16:10

1 Answers1

0

You can't do this dynamically without eval. Even then, you'd likely use the variable names statically—it's totally useless. You may as well destructure properly:

let o = { a: 'a', b: 'b' };
let { a, b } = o;
console.log(a, b);
Rafael
  • 7,605
  • 13
  • 31
  • 46