Home > Software design >  Jquery Array in object value
Jquery Array in object value

Time:12-02

I'm sorry if I get the terminology wrong, I always mix up object and arrays, but what I'm looking for is how to dynamically add to an array within an object value.

var objs = { unit: {x1, x2, x3}, tm:{y1, y2, y3} }

When a button is clicked I want to add it to the appropriate object.

<button id="btn1" class="btn" for="unit" value="val4">
<button id="btn2" class="btn" for="dept" value="xyz1">

When this button is clicked, it tries to find the "for" and add the value.

$(document).on('click','.btn',function(){
     var fot = $(this).attr('for')
     var val = $(this).attr('value')

     //here's where I'm having issues
     ?? if (fot in objs) {
        // if the key is already in objs then add to the value array
           objs[fot].push({val})
     } else {
        // if key is not in objs then add the key and the value as an array
           objs.push({ [fot]:val })
     }
});

The outcome of clicking the button#btn1

objs = { unit: {x1, x2, x3, **val4**}, tm: {y1, y2, y3} }

The outcome of clicking the button#btn2

objs = { unit: {x1, x2, x3, val4}, tm: {y1, y2, y3}, **dept: {xyz1}** }

each error: enter image description here

CodePudding user response:

Objects are for key/values, so something like { foo: "bar" } - and not just { foo }. If you are just keeping a list of variables or values, use an array. Here's a method for that.

var objs = {
  unit: ['x1', 'x2', 'x3'],
  tm: ['y1', 'y2', 'y3']
}

$(document).on('click', '.btn', function() {
  var fot = $(this).attr('for')
  if (!objs[fot]) objs[fot] = [];
  if (!objs[fot].find(a => a === $(this).val())) objs[fot].push($(this).val())
 // console.log(objs)
  $.each(objs,function(i,v) { console.log('log:', i,v) })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1" class="btn" for="unit" value="val4">Add val4 to unit</button>
<button id="btn2" class="btn" for="dept" value="xyz1">Add xyz1 to dept</button>
<button id="btn3" class="btn" for="newthing" value="xyz1">Add xyz1 to newthing</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related