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?
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
In JavaScript, an object consists of key-value pairs where keys are similar to indexes in an array and are unique. If one tries to add a duplicate key with a different value, then the previous value for that key is overwritten by the new value.
Objects are Variables JavaScript variables can also contain many values. Objects are variables too. But objects can contain many values.
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.
If you have an array of key names, you can use Array.reduce():
const keyArray = ['foo', 'bar', 'other'];
const requiredObject = keyArray.reduce((obj, val) => {
obj[val] = val;
return obj;
}, {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With