0

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 (here reg) 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);
 }
Overdose
  • 585
  • 7
  • 30
  • what are the rules for adding `[100, 101], 1010 : [100, 101, 102], 2050 : [100, 102]]` – Kunal Mukherjee May 20 '19 at 15:18
  • As i explained in the question : i have checkboxes for all the combinations, i the values i retrieve are those the user check and submits. So, in my example, the checkbox with `data-reg=1000 data-ag=100` would have been checked, but not the checkbox with `data-reg=1000 data-ag=102` – Overdose May 20 '19 at 15:22
  • 1
    Possible duplicate of [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Heretic Monkey May 20 '19 at 15:48

1 Answers1

-1

To set a property of an object, use bracket notation:

obj[name] = value;
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964