dropWizard
dropWizard

Reputation: 3538

Javascript: adding a dictionary to a list

I have this simple dictionary:

var x = {'pitchName': 'pitch1'}

console.log(x.pitchName)
>> pitch1

Now I want to create a dictionary for something like:

{x.pitchName : 'data'}

However that throws and error.

If I try:

var z = x.pitchName {z: 'data'}

that just returns:

{z: 'data'}

How can I create a dictionary where the key is the value of a previous dictionary? End goal is:

{pitch1: 'data'}

Upvotes: 0

Views: 440

Answers (1)

DocMax
DocMax

Reputation: 12164

The object literal turns the keys into strings. In your case, you want to use a variable as the key, so you need to do it in two steps:

var z = {};
z[x.pitchName] = 'data';

As CRice noted in a comment on the question, you can also use a computed property, provided you are using ES2015. More on that can be found on the MDN page for Object Initializers. The syntax there would look like:

var z = {[x.pitchName]: 'data'};

Upvotes: 4

Related Questions