6
LeMeow
5y

const obj = {
a:5,
b:25
}

const {...Object.keys(obj)} = obj;
console.log(a);

It would have been cool if that worked 😅

Comments
  • 1
    Trying to think of reasons as to why this doesn't work.

    I have not tried it myself, but it would have been pretty cool.
  • 0
    PHP can do that: http://php.net/manual/en/...

    Why it's not a good idea: there aren't really many use cases; it clutters scope; when used on user-provided data it leads to disasters.
  • 0
    There's a with(obj){ console.log(a) } for exactly that purpose. Hold on, don't rush to use it just yet; trust me, you won't like it as much as you think.

    You'll spend hours on end trying to figure where some value comes from, before eventually realising your object has a property with a colliding name you've added for X purpose. Then you'll spend hours figuring out "Cannot read X of undefined" in production, because of minification. And on top of that, every time browsers add support for some new method / property, there will be a chance it causes name collision in your code. So just stick with expanding the variables you need, or prepend the object, it's not worth the trouble...
  • 0
    With JavaScript, use the spread operator.
    Although the variables will still have to be named by the user.

    Reason why the user will have to always name variables on his own is scope -
    You have 2 objects with same properties, does the second object replace the value taken off the first?
Add Comment