views:

50

answers:

2

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!"); } }
];
+2  A: 
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) {};
Justin Johnson
+2  A: 

JavaScript object literals expect the keys to be either an Identifier, a String literal or a Number literal, a workaround can be to build your object step by step, using the bracket notation:

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

Note that the above isn't JSON.

JSON is a language-agnostic data interchange format, its grammar differs from the JavaScript Object literals, basically by allowing only string keys and the values must be an object, array, number, string, or the literal names: false, null true.

CMS
Why object inside an array? Wouldn't `var myMenu = {}; myMenu[LOC.MENU_TITLE]` work as well?
Tatu Ulmanen
Yes, I'm just following the structure that the OP has `var myMenu= [ .... ];`
CMS
The structure is from the jQuery ContextMenu plugin
Daok
This doesn't work, but Justin Johnson solution works. Trying to understand why...
Daok