Jeach
Jeach

Reputation: 9042

How to add a property to an object using the ['key'] notation?

JavaScript documentations states that in order to add a property to an existing object you could do the following.

data["property"] = value;

or

data.property = value;

In my case, I'm trying to convert my model ID (received by the server) to string before adding it, such as:

data.model[id.toString()] = false;

But I get the following error:

Uncaught TypeError: Cannot set property '1' of undefined

I initially though that it was because you couldn't use an alphanumeric string or some kind of weird limitation, so I tried prefixing my ID with a letter, such as:

var id = 'k' + id.toString();

Still doesn't work! But when I use Chrome's Console panel and do it manually, such as:

var data = {};
var data['1'] = false;

That works, so what am I doing wrong?

What is the official name for data.['key'] = value; operations anyway? It would help knowing when trying to Google for help.


Update 1: Ok, it seems that it may be due to the following:

var data = localStorage.getItem('model.state');

When I change it to:

var data = {};

It suddenly started to work!


Update 2: I see what I'm doing wrong (but still not sure why it was giving me an 'undefined' error... anyone?).

I did the following:

var data = localStorage.getItem('model.state');
if (data) data = JSON.parse(data);

And it started to work as expected. Sorry about that... thanks for the help everyone!

Upvotes: 1

Views: 74

Answers (1)

Minko Gechev
Minko Gechev

Reputation: 25682

You get this error because data.model is not defined. In order to prevent the thrown error you can use:

data.model = data.model || {};
data.model[id.toString()] = false;

This is the short version of:

if (!data.model) {
  data.model = {};
}
data.model[id.toString()] = false;

Upvotes: 7

Related Questions