0

I would like to have an array like this:

array['parameter1'] = 1,2,3,4
array['parameter2'] = A,B,C,D

(simple construction as explanation)

And I would like to call it later like:

alert(array['parameter2']) to get "A,B,C,D"

At the moment, I have a simple array:

var array = [];
$.each($("input[name='checkbox']:checked"), function(){            
   array.push($(this).val());
});

But this doesn't help. Need help please :)

yaken
  • 559
  • 4
  • 17
Trombone0904
  • 4,132
  • 8
  • 51
  • 104

4 Answers4

1

You don't use associative arrays in Javascript because

If you use named indexes, JavaScript will redefine the array to a standard object. After that, some array methods and properties will produce incorrect results.

For that purpose you will use objects.

You can write it like this:

let obj = {
    parameter1: ["A", "B", "C", "D"],
    parameter2: [1, 2, 3, 4]
}

You can also assign new parameters to your object by saying:

obj.parameter3 = [5, 6] //some values in that array.

or

obj["parameter3"] = [5, 6]

If you want to get the value from object, you can access it like this:

console.log(obj.parameter1)
Mirakurun
  • 4,859
  • 5
  • 16
  • 32
1

Here is how you should initialize your object so that it makes your logic easier.

The code snippet here also shows how you can call each array inside the parameter object.

let parameters = {
  parameter1: [1, 2, 3, 4],
  parameter2: ['A', 'B', 'C', 'D']
}
console.log(parameters)
console.log(parameters['parameter1'])
console.log(parameters['parameter2'])
holydragon
  • 6,158
  • 6
  • 39
  • 62
0

You can use javascript objects instead of an array. Objects contain a key and a value. You can think of an object being like an array (in fact arrays are actually objects under the hood in JS), but instead of using indexes to access elements, you use keys.

Taking your example from above you can use an object like so:

var obj = {}; // create empty object to add key-value pairs into
obj["parameter2"] = "A,B,C,D"; // add a key-value pair into the object

The above notation means, set the key to be paramter2 which has the value of "A,B,C,D". Now you can use obj["parameter2"] (or obj.parameter2) to access the value stored at the key paremeter2.

See runnable example below:

var obj = {}
obj["parameter1"] = "1,2,3,4";
obj["parameter2"] = "A,B,C,D";

console.log(obj["parameter1"]);
console.log(obj["parameter2"]);
console.log(obj.parameter2); // same as above (accessing value using dot notation)
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

Array indices are based on a number. You can add named index, but that would lead to undesired scenarios. You can read more about it here

For your case, I would suggest you to use an object. example:

var yourObj = {}
//If you want to push some data
if(yourObj.parameter1){
    yourObj.parameter1 = ['My Value 2']
}
else{
    yourObj.parameter1.push('My Value 2')
}

console.log(yourObj.parameter1)
Ashish
  • 4,206
  • 16
  • 45