1

I am trying to create a JSON object with values of list of check boxes.

The key attribute of the object should be the checkbox id, i am getting it like this.

var elementId = $(this).attr("id");

This is my complete code.

var ImportParameters = [];
 $('#divImportOptions .ace').each(function (index, obj) {
 debugger;
 var elementId = $(this).attr("id");
 var elementValue = $(this).is(':checked');
 ImportParameters.push({ elementId : elementValue }); 
 });

My output currently is like this.

{elementId: true}

My Required output is like this

{ chkAllowDetailsInfo : true}

What should i do in order to get the desired output ?

asked Jul 9, 2018 at 7:12

1 Answer 1

2

You can use map() to create an array from a collection of jQuery objects. To use a variable as the key of an object, wrap it in braces, []:

var importParameters = $('#divImportOptions .ace').map(function() {
 return { [this.id]: this.checked }; 
}).get();
console.log(importParameters);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divImportOptions">
 <input type="checkbox" id="foo" class="ace" value="A" checked="true" />
 <input type="checkbox" id="bar" class="ace" value="B" />
 <input type="checkbox" id="fizz" class="ace" value="C" checked= "true" />
 <input type="checkbox" id="buzz" class="ace" value="D" />
</div>

answered Jul 9, 2018 at 7:15
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.