6

It's a little bit difficult to explain what I need, so I'll use some non-working code:

function createSimpleObjet(name, value){
    return {
        name: value
    };
}

//create it
var obj = createSimpleObject('Message', 'Hello World!');
//test it:
alert(ojb.Message); //should alert 'Hello World!'

How would I go about?

Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
  • 1
    possible duplicate of [create object using variables for property name](http://stackoverflow.com/questions/3153969/create-object-using-variables-for-property-name) – Felix Kling May 21 '12 at 10:01
  • See also [Using constants as indices for JavaScript associative arrays](http://stackoverflow.com/questions/4117214/using-constants-as-indices-for-javascript-associative-arrays/4117231#4117231). – Asherah May 21 '12 at 10:15
  • Yeah, I see. Really difficult to search where you are looking when one doens't know how do call it :D – Kees C. Bakker May 21 '12 at 10:29

2 Answers2

12

In order to do this try square bracket notation:

function createSimpleObject(name, value){
    var obj = {};
    obj[name] = value;
    return obj;
}
VisioN
  • 143,310
  • 32
  • 282
  • 281
4

You can't use a variable as a property name in an object literal. You have to create the object, and then assign the value using square bracket notation.

var object = {};
object[name] = value;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335