Javascript Jquery在数组中创建数组

Javascript Jquery在数组中创建数组,javascript,jquery,arrays,Javascript,Jquery,Arrays,我有两组复选框,如下所示: <ul id="searchFilter"> <li class=""> <input type="checkbox" name="location[]" class="cb_location" value="1">Toronto</li> <li class=""> <input type="checkbox" name="location[]" cla

我有两组复选框,如下所示:

<ul id="searchFilter">
    <li class="">
        <input type="checkbox" name="location[]" class="cb_location" value="1">Toronto</li>
    <li class="">
        <input type="checkbox" name="location[]" class="cb_location" value="3">New York</li>
    <li class="">
        <input type="checkbox" name="location[]" class="cb_location" value="6">London</li>
    <li class="">
        <input type="checkbox" name="location[]" class="cb_location" value="5">Paris</li>
    <li class="">
        <input type="checkbox" name="location[]" class="cb_location" value="4">Berlin</li>
</ul>

        <ul id="searchFilter">
                    <li><input type="checkbox" name="price[]" class="cb_price" value="2"> $200,000 to $299,999</li>
                    <li><input type="checkbox" name="price[]" class="cb_price" value="3"> $300,000 to $399,999</li>
                    <li><input type="checkbox" name="price[]" class="cb_price" value="4"> $400,000 to $499,999</li>
                    <li><input type="checkbox" name="price[]" class="cb_price" value="5"> $500,000+</li>
                </ul>
但这将返回复选框值的值,无论它们位于哪一组复选框中,我的问题是如何将它们分开,但在opts数组中,我正在寻找这些结果:

[位置[1,2,3],价格[1,2,3]]


这里有一个小问题:

如果复选框集足够小,并且事先知道,只需分别评估它们中的每一个:

function getValues(selector) {
    var $checked = $(':checkbox:checked');
    if (selector) {
        $checked = $checked.filter(selector);
    }

    return $checked.map(function() {
        return this.value;
    }).get();
};

$(':checked').on('change', function() {
    console.log({
        location: getValues('.cb_location'),
        price: getValues('.cb_price');
    });
});

要创建这样的复杂对象,您需要显式地构建它:

$(':checkbox').change(function () {
    var opts = {};
    $(":checkbox:checked").each(function () {
        var name = this.name;
        if (!opts[name]) opts[name] = [];
        opts[name].push(this.value);
    });
    console.log(opts);
});

结果将类似于:

{ location[]: [1,2,3], price[]: [4,5,6] }
如果需要,可以从循环内的复选框名称中删除
[]

var name = this.name.substring(0,this.name.length-2);

数组不能看起来像那样。你是说你想要一件东西吗<代码>{location:[1,2,3],price:[4,5,6]}NB:这不会为一组未选中选项的复选框生成密钥。@Alnitak OP没有要求这样做。“选中复选框的值”值,而不是未选中复选框的名称。尽管如此,它仍然是。
var name = this.name.substring(0,this.name.length-2);