You cannot refer to other keys on the object within a literal definition. The options for setting a key based on other keys or other values within the object are:
Use a getter function for the key that can return a value based on other properties.
Use a regular function for the key that can return a value based on other properties.
Assign a key/value outside of the literal definition where you can assign a static value based on the other keys/properties.
Here are examples of each of these options:
// use getters for properties that can base their values on other properties
var myHash = {
key1: 5,
get key2() { return this.key1 * 7; },
key3: true,
get key4() { return this.key3 ? "yes" : "no";}
};
console.log(myHash.key2); // 35
// use regular functions for properties that can base
// their values on other properties
var myHash = {
key1: 5,
key2: function() { return this.key1 * 7; },
key3: true,
key4: function() { return this.key3 ? "yes" : "no";}
};
console.log(myHash.key2()); // 35
// assign static properties outside the literal definition
// that can base their values on other properties
var myHash = {
key1: 5,
key3: true
};
myHash.key2 = myHash.key1 * 7;
myHash.key4 = myHash.key3 ? "yes" : "no";
console.log(myHash.key2); // 35
Note: the first two options are "live". If you change the value of myHash.key1, then the value of myHash.key2 or myHash.key2() will change too. The third option is static and the values of myHash.key2 will not follow changes in myHash.key1.