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 :)
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.
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.
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.
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
Declare an empty object, then you can use array syntax to assign properties to it dynamically.
var fish = {};
fish[<propertyName>] = <value>;
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With