views:

139

answers:

6

Hi,

Lets say I have the following javascript:

var obj = {
 key1 : "it ",
 key2 : key1 + " works!"
};
alert(obj.key2);

This errors with "key1 is not defined". I have tried

this.key1
this[key1]
obj.key1
obj[key1]
this["key1"]
obj["key1"]

and they never seem to be defined.

How can I get key2 to refer to key1's value?

+2  A: 

This is not JSON. JSON was designed to be simple; allowing arbitrary expressions is not simple.

In full JavaScript, I don't think you can do this directly. You cannot refer to this until the object called obj is fully constructed. So you need a workaround, that someone with more JavaScript-fu than I will provide.

Thomas
+4  A: 

You can't refer to a property of an object before you have initialized that object; use an external variable.

var key1 = "it";
var obj = {
  key1 : key1,
  key2 : key1 + " works!"
};

Also, this is not a "JSON object"; it is a Javascript object. JSON is a method of representing an object with a string (which happens to be valid Javascript code).

Tgr
+2  A: 

That's not a JSON object, that's a Javascript object created via object literal notation. (JSON is a subset of object literal notation.)

As far as I'm aware, there's no way within the object literal to refer to another key of that same literal, because there's no reference to the object being created yet.

T.J. Crowder
+1  A: 

Maybe you can think about removing the attribute to a function. I mean something like this:

var obj = {
 key1 : "it ",
 key2 : function() {return this.key1 + " works!";}
};

alert(obj.key2());
burak ozdogan
+1  A: 

Because the statement defining obj hasn't finished, key1 doesn't exist yet. Consider this solution:

var obj = { key1: "it" };
obj.key2 = obj.key1 + ' ' + 'works!';
// obj.key2 is now 'it works!'
Delan Azabani
+2  A: 

This can be achieved by using constructor function instead of literal

var o = new function() {
  this.foo = "it";
  this.bar = this.foo + " works"
}

alert(o.bar)
stereofrog