Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a javascript associative array { } with dynamic key names?

Tags:

jquery

Basically I have a loop incrementing i, and I want to do this:

var fish = { 'fishInfo[' + i + '][0]': 6 };

however it does not work.

Any ideas how to do this? I want the result to be

fish is { 'fishInfo[0][0]': 6 };
fish is { 'fishInfo[1][0]': 6 };
fish is { 'fishInfo[2][0]': 6 };

etc.

I am using $.merge to combine them if you think why on earth is he doing that :)

like image 400
NibblyPig Avatar asked Jan 06 '12 12:01

NibblyPig


People also ask

How to add a key to an associative array dynamically?

Javascript's associative arrays are nothing but javascript object literals. You can add keys to these objects dynamically if the key is a string using the square brackets notation.

How to handle associative arrays in JavaScript?

The first and most correct way to handle associative arrays in JavaScript is to create a Map object. This method has several advantages over regular objects, such as the fact that keys are not limited to strings - they can be functions, other objects, and pretty much any other primitive.

How do I create associative keys in JavaScript?

You need to set a string to keyValuePair [0] and use that as the associative key. That is the only way I got mine to work. After you have set it up, you can either refer to it with numeric index or key in quotes. All modern browsers support a Map, which is a key/value data structure.

How to add a new key to an array in JavaScript?

Using bracket syntax to add new property (Old Way but still powerful ) So, this is the way where we can add a new key to the existing object like the way we used to access the array. 2. Using Object.defineProperty () method This method is useful when your key is also dynamic. 3. Using ES6 [] method


2 Answers

Declare an empty object, then you can use array syntax to assign properties to it dynamically.

var fish = {};

fish[<propertyName>] = <value>;
like image 119
nikc.org Avatar answered Oct 27 '22 18:10

nikc.org


Do this:

var fish = {};
fish['fishInfo[' + i + '][0]'] =  6;

It works, because you can read & write to objects using square brackets notation like this:

my_object[key] = value;

and this:

alert(my_object[key]);
like image 21
Tadeck Avatar answered Oct 27 '22 17:10

Tadeck