How to create javascript associative array {} with dynamic key names?

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

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

however this will 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 }; 

and etc.

I use $ .merge to combine them if you think why he does it :)

+6
source share
4 answers

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

 var fish = {}; fish[<propertyName>] = <value>; 
+9
source

Do it:

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

This works because you can read and write objects using square brackets, such as:

 my_object[key] = value; 

and this:

 alert(my_object[key]); 
+5
source

For any dynamic objects with object keys, you need parenthesis notation.

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

Multidimensional arrays in javascript are created by storing the array inside the array.

Try:

 var multiDimArray = []; for(var x=0; x<10; x++){ multiDimArray[x]=[]; multiDimArray[x][0]=6; } 

Script Screen: http://jsfiddle.net/CyK6E/

0
source

Source: https://habr.com/ru/post/905308/


All Articles