Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jquery Array in object value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$(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}** }

>Solution :

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)
});
<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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading