Javascript: adding a dictionary to a list


69 просмотра

1 ответ

1247 Репутация автора

I have this simple dictionary:

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

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

Автор: Morgan Allen Источник Размещён: 08.11.2017 11:59

Ответы (1)

4 плюса

10630 Репутация автора


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'};
Автор: DocMax Размещён: 09.11.2017 12:12
Вопросы из категории :