How to push checkbox checked values to js object using jquery each function?

I want the checked checkbox values to store in food javascript object like below:

food: {
{id: 1, name: egg }
{id: 2, name: meat}

Here’s my code:

var exclude_foods = {};

   exclude_foods = Object.assign(exclude_foods, {
     id: 1,
     name: jQuery(this).val(),

Any suggestion or help?

>Solution :

You can use jQuery’s map() method to do what you require.

Note that it’s not clear where the id value is intended to come from, so I set it to the index of the checkbox for this example. This can easily be amended to suit your use case.

$('button').on('click', e => {
  var exclude_foods = {
    foods: $('input[name="exclude_food"]:checked').map((i, el) => ({
      id: i,
      name: el.value
<script src=""></script>
   <input type="checkbox" name="exclude_food" value="egg" />
   <input type="checkbox" name="exclude_food" value="meat" />
   <input type="checkbox" name="exclude_food" value="nuts" />

<button>Get values</button>

Leave a Reply