JavaScript array of key / value pairs uses the literal variable name for the key

I am trying to create an array of key / value pairs using the push method, but I get unexpected results.

console.log prints this:

books: [{"bookTitle": "Mark Twain"}]

While I would expect this:

books: [{"Tom Sawyer": "Mark Twain"}]

Here is the code:

 var books = []; var bookTitle = "Tom Sawyer"; var author = "Mark Twain"; books.push({bookTitle : author}) console.log("books: %s", JSON.stringify(books)) 

I tried books.bookTitle = author and books[bookTitle] = author , but the result is the same. Any help is appreciated.

+13
source share
2 answers

A parenthesis designation is the correct way to use a dynamic key name:

 books[bookTitle] = author 

However, you need to use an intermediate object:

 var books = []; var bookTitle = "Tom Sawyer"; var author = "Mark Twain"; var foo = {}; foo[bookTitle] = author; books.push(foo); console.log("books: %s", JSON.stringify(books)) 
+23
source

In modern Javascript (ES2015 +), you can use the computed properties , which slightly modifies your sample code - square brackets are wrapped around the key name to indicate it must be calculated before the assignment:

 var books = []; var bookTitle = "Tom Sawyer"; var author = "Mark Twain"; books.push({[bookTitle] : author}) 

... which correctly gives:

[{"Tom Sawyer": "Mark Twain"}

This is similar to Matt Ball's original answer, but avoids the verbosity of using temporary variables.

+5
source

Source: https://habr.com/ru/post/1401899/


All Articles