0

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'}

2
  • 2
    var obj = {[x.pitchName]: 'data'}? Commented Nov 9, 2017 at 0:00
  • @CRice, Thanks for mentioning the computed property syntax. It was new to me. Commented Nov 9, 2017 at 0:18

1 Answer 1

4

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'};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.