I\'m trying to create an array of key/value pairs by using the push method, but getting unexpected results.
console.log prints this:
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.