I need to build a dynamic associative in the following way:
I have a variable named param
var arr = { param's value : "another value"};
I am unable to put param's value as the key.
Thanks and regards!
I need to build a dynamic associative in the following way:
I have a variable named param
var arr = { param's value : "another value"};
I am unable to put param's value as the key.
Thanks and regards!
Try this.
var arr = {};
arr[ param + "'s value"] = "another value";
Note: 'var arr = {}', here arr is Object instead of array. see
It's unclear what you're asking, but taking a stab at it: If you mean you have a variable, param
, and want to use its value (just its value) as a property name:
var obj = {}; // Note "obj", not "arr" -- it's not an array
obj[param] = "another value";
That works because in JavaScript you can access the property of an object using both "dot" notation and a literal (obj.foo
), or bracketed notation and a string (obj["foo"]
). In the second case, the string can be result of any expression, and the constraints on property names that apply to literals don't apply (because we're not using a literal).
Just put the key in quotes:
var arr = { "param's value" : "another value"};
Do you just want to use the value stored in the variable param
as a key ?
If so:
var param = 'something',
myObject = {};
myObject[param] = 'something else';
Technically it's an object {}
an array is written with (square)brackets []
.
Setting a new prop or editing one on an object can be done so:
var obj = {};
obj.key = 'value';
// or
obj['key'] = 'value';
//object inside an object.
var obj = {};
obj.objNested = {
key: 'value'
};
// or
obj.objNested = {};
obj.objNested.key = 'value';
// or with a variable;
var obj = {};
var key = 'prop';
obj[key] = 'value';
// an array containing objects:
var array = [
{ key: value },
{ key: value }
];