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
Hudhaifa Yoosuf
9192 gold badges13 silver badges28 bronze badges
1 Answer 1
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
Rory McCrossan
338k41 gold badges322 silver badges353 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js