-1

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

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

7 Comments

PERFECT! Thank you very much!
There was a small typo which I just corrected... ...find(a => a === $(this).val())...
How do I run through these? $.each(objs,function(i,v) { console.log(i) } it's not showing anything - like it's not looping through.
$.each(objs,function(i,v) { console.log('log:', i,v) })?
It's not logging anything. If is console.log(objs) $.each(objs,function(i,v) { console.log(i,v) }) but I only get the objs (put the console in the question)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.