Create an object with same key and value, without duplicating the data
But, how can we create the same object without having the key variable?
I want to have something like
{ foo: "foo" }
. I triedobj = { "foo" }
, but that throws.
You can't. You'll have to specify both the name and value, if you don't already have a variable with the name you want and the value you want (as you do with the initial example in your question).
If your starting point is the string literal "foo"
, you have to either assign it to a variable and use that (var x = "foo"; var obj = {}; obj[x] = x;
), or write foo
twice (var obj = {foo: "foo"}
).
But you said you didn't want to do either of those things, so the answer is: You can't.