在JavaScript中将对象键设置为动态值

3

我正在遍历一个jQuery选择器,并试图将表单元素的值赋给一个容器变量,该变量可以作为JSON传递给进一步的操作。

假设有三组复选框,每组复选框都在自己的div中,分别命名为group1、group2和group3。

这是伪代码,但类似于以下内容:

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?
    });
}

因此,我希望将所选项目的值添加到data对象中的正确项目中--例如。如果我们正在循环处理group1 div,则每个组的复选框将添加到data.group1data.group2等。

如何使data.index评估为data.group1


2个回答

7

就像这样简单:

data[index]

.......


很好的恶作剧@alex :) 即使在像这样已知且安全的输入情况下,不使用eval的一个真正原因是它太慢了。 - nickf
@cbayram:我相信那个声望为120k(其中大部分来自JavaScript徽章)的人知道这一点;-) - zerkms
@zerkms 或许答案应该是 data['group' + (index + 1)] - nickf
@zerkms,我没明白。不过看到一些幽默和恶搞还是很好的,正是我想要的先例哈哈。 - cbayram
@Alex——因为他希望他的宠物能够活下去。 - RobG
显示剩余5条评论

0

如果您能够使用ES6 JavaScript功能,您可以使用计算属性名称来轻松处理此问题:

var request = {id : 1236};
var responseMessage = 'The response message';

var resp = {responses: {[request.id]: responseMessage}};

[request.id] 对象键具有动态值


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接