Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Array of Key/Value Pairs Uses Literal Variable Name for Key

Tags:

javascript

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.

like image 755
Raj Avatar asked Aug 28 '13 15:08

Raj


People also ask

Do arrays use key value pairs?

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.

Can I use a variable as a key JavaScript?

Use Variable as Key for Objects in JavaScript log(obj. key); console. log(obj["key"]); The variable varr was set as the key for the object obj .

What is a key value pair called in JavaScript?

A property is a “key: value” pair, where key is a string (also called a “property name”), and value can be anything. We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by the key.

What is the keys of an array in JavaScript?

The array. keys() method is used to return a new array iterator which contains the keys for each index in the given input array. Parameters: This method does not accept any parameters. Return Values: It returns a new array iterator.


2 Answers

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))
like image 107
Matt Ball Avatar answered Oct 14 '22 07:10

Matt Ball


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.

like image 25
Lee Benson Avatar answered Oct 14 '22 05:10

Lee Benson