Suppose we have two arrays containing possible numerical values:
var reg = [1000, 1010, 2050];
var ag = [100, 101, 102];
The objective is to create an object/json structure like this:
{ 1000 : [100, 101], 1010 : [100, 101, 102], 2050 : [100, 102]};
These values will be obtained from checkboxes that the user selects:
<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' represent all possible values from the arrays.
var obj = {}; //or var arr = [];
$('.agcheck:checked').each(function(){
var ag = parseInt($(this).data('ag'));
var reg = parseInt($(this).data('reg'));
// What needs to be done here
}
How can we achieve this object structure in JavaScript?
Within the loop:
- We cannot use
obj.reg.push(ag)
because it would result in "Cannot read property 'push' of undefined" - We cannot use
obj.push(reg:ag)
as it would lead to an array like[0:[reg:100], 1:[reg:101]...]
with the key not being set correctly - We don't want
obj.push({'reg':reg,'ag':ag})
either, because we want the reg value to act as the key.
====
With the help of #SLaks's answer, I was able to solve this issue:
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);
}