-1

I'm making a chrome extension and two of the js files are-

  • constants.js
  • main.js

In constants.js, I've defined an object -

var infoPostJsonParamNames = {"pid" : "PID",
                              "title" : "title_value",
                              "price" : "price",
                             };

And in main.js, I'm using the values in infoPostJsonParamNames as keys of other objects, like -

    dataI = new Object();
    dataI.infoPostJsonParamNames["title"] = "Title value";
    dataI.infoPostJsonParamNames["cost"] = 12.34;

The reason behind doing this is that I've to use the same names of the keys (for example in POST requests), i.e. PID, title_value and price, in many places in the code but it may change in the future, for example, title_value can become TITLE_v. So I am trying to avoid changing them in many places by changing them in only one place, i.e. in the object infoPostJsonParamNames.

But doing this gives me the error:

TypeError: Cannot set property 'title' of undefined

2 Answers2

1

What you are trying to do is to set a property name dynamically. You have to use bracket access; The following example should clarify it.

dataI = new Object(); // or {} for style points;
var titlePropertyName = infoPostJsonParamNames.title;
dataI[titlePropertyName] = "Title value";

What your code was previously doing was looking for a property called infoPostJsonParamNames in your dataI object. That property didn't exist so it caused an error when it tried to access a sub property called title.

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

You missed infoPostJsonParamNames initialisation inside dataI scope.

dataI = {};
dataI.infoPostJsonParamNames = {};
dataI.infoPostJsonParamNames["title"] = "Title value";
dataI.infoPostJsonParamNames["cost"] = 12.34;

By the way, you can do the same like this:

dataI = {
  infoPostJsonParamNames: {
    title: = "TitleValue",
    cost: 12.34
  }
}
Jan Cássio
  • 2,076
  • 29
  • 41
  • The OP is using `infoPostJsonParamNames` as an easy way to allow the HTTP parameter names to be changed from a single place. – Ruan Mendes Dec 07 '15 at 16:33