Amit Erandole
Amit Erandole

Reputation: 12281

How does this javascript object array work?

I am trying to understand something very basic. If I have an object like this:

var topics = {}

And I do this:

topics[name] = ["chapter 1", "chapter 2", "chapter 3"];

When I log this object, I don't see the name attribute. What have I done exactly? Have I created a key called name with the value of an array?

Of course I know I can do that by just doing

topics.name =  ["chapter 1", "chapter 2", "chapter 3"];

But then what is this doing?

topics[name] = ["chapter 1", "chapter 2", "chapter 3"];

Could someone please clarify?

Upvotes: 2

Views: 165

Answers (6)

Joseph Marikle
Joseph Marikle

Reputation: 78590

The resulting structure can be seen in the following screen capture. As stated by mck89, you probably want to use the "name" syntax

enter image description here

Upvotes: 2

pimvdb
pimvdb

Reputation: 154968

There are generally three ways to distinguish:

topics.name
topics["name"]
topics[name]

The first two are equivalent. So .xxx represents the literal key xxx, as does ["xxx"].

The last one will use whatever the name variable contains. E.g.:

var name = "test";
topics[name] = 123; // topics["test"] now exists

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270775

If your code did not result in a ReferenceError, you may have already had a variable in global scope named name, and created a new property of name's contents.

Upvotes: 1

Amadan
Amadan

Reputation: 198556

That should generate an error, unless you have variable name defined as a string or a number.

These three are equivalent:

var name = "key";
topics[name] = "value";

topics["key"] = "value";

topics.key = "value";

Upvotes: 3

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196306

When you use the [] notation it expects an expression in between, that translates to a string.

Using name not enclosed in quotes 'name' it assumes you are using a variable called name.

Which in your case is undefined.

The correct usage would be

topics["name"] = ["chapter 1", "chapter 2", "chapter 3"];

If you want to use a variable you can do things like

var prop = 'name';
var topics = {};

topics[prop] = ["chapter 1", "chapter 2", "chapter 3"];

this will create the name property on the object.. useful for dynamic/automatic creation/filling of objects..

Upvotes: 3

mck89
mck89

Reputation: 19271

Your are creating a property on the object with a name based on the value of the name variable. If you want to create a property called name in that way you need to do:

topics["name"] = ["chapter 1", "chapter 2", "chapter 3"];

Upvotes: 3

Related Questions