Reputation: 6728
I'm looping through a jQuery selector and trying to assign values of form elements to a container variable that can then be passed along to further actions as JSON.
Say there's three groups of checkboxes, each in their own div, named group1, group2 and group3.
This is psuedo-code, but something like this:
var data = {};
var groups = {
'group1': obj with a bunch of key val pairs for checkboxes,
'group2': another obj,
'group3': and another obj
}; // these define divs / groups of checkboxes
// create all the checkboxes and divs from the groups object somewhere in here
//now build a function to loop over the groups and get any checked boxes
function getInputs(){
$.each(groups, function(index, el) {
// this is where I am stuck
data.index = $('#' + index + ' input:checked'); // <-- how to do this?
});
}
So essentially I want to add the values of the checked items to the proper item in the data
object-- eg. If we're looping over the group1
div, then the checkboxes for each group will be added to data.group1
, data.group2
etc.
How do I make data.index
evaluate as data.group1
?
Upvotes: 3
Views: 8498
Reputation: 10623
If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:
var request = {id : 1236};
var responseMessage = 'The response message';
var resp = {responses: {[request.id]: responseMessage}};
The [request.id] object key has a dynamic value
Upvotes: 0