0
let data = {"a":1,"b":2};

I want to destructure this object to automatically create 2 variable with names equal to key without providing the name. How can I do that? Can I even do that without specifying the keynames?

let {} = data;

console.log(a) should then give 1

Is this possible?

The reason I want this is because I have string , str = `runcode -s ${a} ` I want to get the value of "a" automatically when I run str Even if I change the str to `runcode -s ${data.a} ` and run str, the data.a doesn't get replace by 1. How can I solve this ?

user3439399
  • 195
  • 1
  • 3
  • 13
  • This is just a bad idea. Suppose the object is dynamically generated, this would mean the variable names are going to be dynamically generated as well. – Derek 朕會功夫 Feb 13 '18 at 19:48
  • 1
    No, you can't do that. `with (data) { ... }` is a statement that probably kind of does what you think you want, but shortening code _this_ much hurts readability, as well as performance. Using `with` is only allowed in non-strict-mode for this reason, and "automatic" destructuring is also not possible for this reason. – Patrick Roberts Feb 13 '18 at 19:49
  • The reason I want this is because I have string , str = "runcode -s ${a}" and I want to get the value of "a" automatically when I run `str` Even if I change the str to "runcode -s ${data.a}" and run `str`, the data.a doesn't get replace by 1. How can I solve this – user3439399 Feb 13 '18 at 20:03
  • @user3439399 by using backticks instead of quotes... – Patrick Roberts Feb 13 '18 at 20:08
  • @PatrickRoberts... it's not working. Hence I thought we need to first create a variable with name "a" and only use it that way. Am I wrong? – user3439399 Feb 13 '18 at 20:11
  • `str = "runcode -s ${data.a}";` --> ``str = `runcode -a {data.a}`;`` – Patrick Roberts Feb 13 '18 at 20:13
  • @PatrickRoberts Thats what I had with back ticks. – user3439399 Feb 13 '18 at 20:15
  • Not according to your question. – Patrick Roberts Feb 13 '18 at 20:16
  • It took the ticks away as I didn't escape it. The problem is that it doesn't replace if I use data.a – user3439399 Feb 13 '18 at 20:30
  • @user3439399 Variables are only expanded inside template literals, not old style strings. That's why you have to put backticks around the value of `str`. – Barmar Feb 13 '18 at 21:04
  • possible duplicate of [How do I destructure all properties into the current scope/closure in ES2015?](https://stackoverflow.com/q/31907970/1048572) - no, you cannot do that. – Bergi Feb 13 '18 at 22:10

1 Answers1

1

Not sure what you're trying to achieve but you could do it the "old fashioned" way:

let str = "runcode -s " + data.a;

or the ES6 way:

let str = `runcode -s ${data.a}`;

with backticks and ${obj.prop}.

Edit: This is not answering the posters original question asked in the topic. This is just a suggestion on how to solve the problem. Sorry for any inconvenience caused.