javascriptobjectecmascript-6

Create an object with same key and value, without duplicating the data


In ES6, we can do:

const key = "foo"
const myObj = { key }
myObj
// => { foo: "foo" }

So, { key } is equivalent with { key: key }.

But, how can we create the same object without having the key variable?

I want to have something like { foo: "foo" }. I tried obj = { "foo" }, but that throws.

What's the right way to build this object, without using a variable and without duplicating the foo word?


Solution

  • But, how can we create the same object without having the key variable?

    I want to have something like { foo: "foo" }. I tried obj = { "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.