简体   繁体   中英

JS : Create a json with dynamic keys and values

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

要设置对象的属性,请使用方括号表示法:

obj[name] = value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM