Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 529
Ionică Bizău Avatar asked Aug 22 '17 14:08

Ionică Bizău


People also ask

How do you add the same key to an object?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

Can JavaScript objects have duplicate keys?

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.

Can an object have multiple values?

Objects are Variables JavaScript variables can also contain many values. Objects are variables too. But objects can contain many values.


2 Answers

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.

like image 194
T.J. Crowder Avatar answered Nov 15 '22 00:11

T.J. Crowder


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;
}, {});
like image 40
Vinayak Bagaria Avatar answered Nov 14 '22 22:11

Vinayak Bagaria