Hard Fitness
Hard Fitness

Reputation: 452

Jquery creating associative array with dynamic keys and multiple values

Trying to create the following:

array( '12345' => 'A01', 'A02', 'A03'
'22222' => 'B01',
'33333' => 'C01', 'C02')

So basically each key is different generated dynamically from another array. Let's say variable numbers has '12345' after certain event is fired.

We have an array called location, this one will have for example ('A01', 'A02', 'A03')

So then on a master array it will map both numbers with the location. This is the array that i will need to save each time there is an event.

The on the next event execution we shall get a new value on numbers variable such as '22222' and then a new array location will overwrite the other one with ('B01') for example and so on.

Remember the keys are gonna be always dynamic and the values can be from 1 to 50 for example we don't know. I know this is more like Object Literals on Jquery. thx in advance.

Here is the piece of code, need to be able to get the key and values

             $.each(dragarray, function(index, value) {

                    dragid_loc['value'] = [];
                    // do loop to add each element of other array
                    $.each(draglocation, function(index2, value2) {
                        dragid_loc.value.push(value2);
                    });

            });

            console.log(dragid_loc);

This line seems to cause the problem i won't push the values of another array draglocation into each. Need to get the key and the value.

dragid_loc.value.push(value2);

Upvotes: 0

Views: 14991

Answers (2)

Mitali
Mitali

Reputation: 2435

var Obj={}

var val1='12345';

Obj[val1]={0:'A01',1:'A02',2:'A03'};

var val2='22222';

Obj[val2]={0:'B01'};

alert(JSON.stringify(Obj));

Upvotes: 2

Diego
Diego

Reputation: 16714

Based in the comments I think what you need is:

  • obj["newProp"] = []; // A new property is added to the object with key newProp and an empty array as value
  • obj.newProp.push(newElement); // A new element is added to the array in newProp of object

Upvotes: 6

Related Questions