3

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?

1

2 Answers 2

7

As simple as:

data[index]

.......

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

10 Comments

Why not eval("data." + index)? ;)
@alex: it's only allowed to real js ninjas ;-)
I think what Julio wants is data["group"+index]. @Alex, eval's use is dangerous in nature as it'll execute beyond your requirements. Example: var index = "group1; alert('go **** yourself')"; eval("data." + index); (sorry for being so blunt :)) Now you could go ahead and use it if you can ensure the input won't have harmful code, but why expose yourself to such risk if there is a safer alternative?
Nice trolling @alex :) One real reason not to use eval, even in cases like this where the input is known and safe, is that it's slowwww.
@cbayram: I'm sure the person with 120k reputation (most of which is from javascript badge) knows that ;-)
|
0

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

Comments

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.