Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable value for the key of another object?

I have something like :

var myMenu= [
  {
    'My English Title':function(menuItem,menu) 
                       { ... }
  }];

Now, I want the replace 'My English Title' by an other JSON structure value LOC.MENU_TITLE.

I have try:

var myMenu= [
  {
    LOC.MENU_TITLE:function(menuItem,menu) 
                       { ... }
  }];

But it doesn't work. Any one can give me an hint of how to get JSON value inside a JSON variable?

Edit: This is to use the Context Menu of Jquery but I got a problem with all solutions below and it's when it's time to pass the String for the Separator. It doesn't show the separator because it pass the string into an object instead of just the string.

Example:

var menu1 = [
  {'Option 1':function(menuItem,menu) { alert("You clicked Option 1!"); } },
  $.contextMenu.separator,
  {'Option 2':function(menuItem,menu) { alert("You clicked Option 2!"); } }
];
like image 575
Patrick Desjardins Avatar asked Feb 08 '10 20:02

Patrick Desjardins


People also ask

How can you get the value in an object's key using a variable referencing key?

Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back. Copied!

Can object keys be variables?

JavaScript object key names must adhere to some restrictions to be valid. Key names must either be strings or valid identifier or variable names (i.e. special characters such as - are not allowed in key names that are not strings).


1 Answers

var tempElement = {};
tempElement[ LOC.MENU_TITLE ] = function(menuItem, menu) {};

myMenu = [ tempElement ];

Addressing your edit. Try the following

var myMenu = [ {}, $.contextMenu.separator, {} ];

myMenu[0][ LOC.MENU_TITLE ]  = function(menuItem, menu) {};
myMenu[2][ LOC.MENU_TITLE2 ] = function(menuItem, menu) {};
like image 78
Justin Johnson Avatar answered Nov 09 '22 13:11

Justin Johnson