-1

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!

curious1
  • 14,155
  • 37
  • 130
  • 231

5 Answers5

5

Try this.

var arr = {};
arr[ param + "'s value"] = "another value";

Note: 'var arr = {}', here arr is Object instead of array. see

Community
  • 1
  • 1
Anoop
  • 23,044
  • 10
  • 62
  • 76
5

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).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Just put the key in quotes:

var arr = { "param's value" : "another value"};
user1983983
  • 4,793
  • 2
  • 15
  • 24
2

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';
joews
  • 29,767
  • 10
  • 79
  • 91
1

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 }
];
Rick Lancee
  • 1,629
  • 1
  • 15
  • 20