1

Possible Duplicate:
Using a variable for a Javascript object key

I can't figure out how I am messing this up.

My code gives me the error:

invalid property id

Code:

 return  { this.Obj.itemid :
               {  Color : this.Obj.color,
                  Name : this.Obj.name,
                  Year : this.Obj.year
                }
           };

I need to return these hashes as an array (thus the return), but no matter what I do, it either returns the error above, or the var reference is stringified. I can't actually get the dynamic js value in there as a key.

I've tried this:

" + this.Obj.itemid + "

and this:

var itemid = this.Obj.itemid;
return { itemid : {
         //etc..
    }}

Any ideas?

Community
  • 1
  • 1
james emanon
  • 11,185
  • 11
  • 56
  • 97
  • this and this.Obj etc.. are all great because the right hand assignments are proper. I get all the correct values except the the var: this.Obj.itemid is ALWAYS stringified when on the left hand side - or used as a key. I will review your link; = thanks. – james emanon Nov 01 '12 at 22:20

2 Answers2

7

The problem is that you can't use this.Obj.itemid in that way.

Instead, try something like:

var ret={};
ret[this.Obj.itemid]=
   {
      Color : this.Obj.color,
      Name : this.Obj.name,
      Year : this.Obj.year
   };
return ret;
Joshua Dwire
  • 5,415
  • 5
  • 29
  • 50
4

What appears on the left-hand side of the colon in a property initializer must be a valid identifier, string literal, or numeric literal. It's always used literally. this.Obj.itemid is none of these things.

If you're trying to use the value of this.Obj.itemid as the property name, then:

var ret = {};
ret[this.Obj.itemid] = {
    Color : this.Obj.color,
    Name : this.Obj.name,
    Year : this.Obj.year
};

That takes advantage of the fact that you can use bracketed notation with any expression for the property name. ret[this.Obj.itemid] = ... will create a property on ret whose name is the result of the expression this.Obj.itemid.

Simpler example:

var foo = {};
var b = "bar";
foo[b] = 42;
console.log(foo.bar); // "42"
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875