I'm trying to create an array of key/value pairs by using the push
method, but getting unexpected results.
console.log
prints this:
books: [{"bookTitle":"Mark Twain"}]
Whereas I would expect this:
books: [{"Tom Sawyer" : "Mark Twain"}]
Here's the code:
var books = [];
var bookTitle = "Tom Sawyer";
var author = "Mark Twain";
books.push({bookTitle : author})
console.log("books: %s", JSON.stringify(books))
I've tried books.bookTitle = author
and books[bookTitle] = author
, but the result is the same. Any help is appreciated.
Bracket notation 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))
In modern Javascript (ES2015+), you can use computed properties which modifies your example code in one slight way-- square brackets are wrapped around the key name to signify it should be computed before assignment:
var books = [];
var bookTitle = "Tom Sawyer";
var author = "Mark Twain";
books.push({[bookTitle] : author})
... which correctly yields:
[ { 'Tom Sawyer': 'Mark Twain' }
This is similar to Matt Ball's original answer, but avoids the verbosity of using temporary variables.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.