Jquery creating associative array with dynamic keys and multiple values

大憨熊 提交于 2019-12-12 05:26:31

问题


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);

回答1:


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



回答2:


var Obj={}

var val1='12345';

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

var val2='22222';

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

alert(JSON.stringify(Obj));



来源:https://stackoverflow.com/questions/13631039/jquery-creating-associative-array-with-dynamic-keys-and-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!