Let's say i have 2 arrays of possible numerical values :
var reg = [1000, 1010, 2050];
var ag = [100, 101, 102];
I want to create a object/json of the kind :
[ 1000 : [100, 101], 1010 : [100, 101, 102], 2050 : [100, 102]];
These values would be retrieved from the checkboxes the user would have checked :
<input type="checkbox" data-reg="1000" data-ag="100" class="agcheck" />
<input type="checkbox" data-reg="1000" data-ag="101" class="agcheck" />
...
<input type="checkbox" data-reg="xxx" data-ag="yyy" class="agcheck" />
The xxx and yyy would be all the possible values from the array and
var obj = {}; //or var arr = [];
$('.agcheck:checked').each(function(){
var ag = parseInt($(this).data('ag'));
var reg = parseInt($(this).data('reg'));
//what i need here
}
How can i create such an object in javascript ?
In the loop
- I can't do obj.reg.push(ag) because i would have "Cannot read property 'push' of undefined"
- I can't do obj.push(reg:ag) because i would have an array like
[0:[reg:100], 1:[reg:101]...]
the key (herereg
) would not be set as such - I don't want
obj.push({'reg':reg,'ag':ag})
because i want the key being the reg value.
====
Thanks to the answer of #SLaks i managed to get it right :
var obj = {}; //or var arr = [];
$('.agcheck:checked').each(function(){
var ag = parseInt($(this).data('ag'));
var reg = parseInt($(this).data('reg'));
if (obj[reg] == undefined) {
obj[reg] = [];
}
obj[reg].push(ag);
}