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?
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?
Share Improve this question asked May 21, 2012 at 9:41 Kees C. BakkerKees C. Bakker 33.4k31 gold badges118 silver badges207 bronze badges 3- 1 possible duplicate of create object using variables for property name – Felix Kling Commented May 21, 2012 at 10:01
- See also Using constants as indices for JavaScript associative arrays. – Asherah Commented May 21, 2012 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 Commented May 21, 2012 at 10:29
2 Answers
Reset to default 13In order to do this try square bracket notation:
function createSimpleObject(name, value){
var obj = {};
obj[name] = value;
return obj;
}
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;