首页 > 解决方案 > 如何从嵌套复选框中获取对象数组中的值?

问题描述

在我的网站中,我有一个从 JSON 动态生成的复选框树,现在我需要在以下对象中获取选中的值,这些值将成为这样的对象数组:

var config = {
    negozio: 1,
    cassa: [{
        CS: 1,
        operatore: []
    }]    
};

negozio 是顶级父复选框 cassa 是第一个子复选框,它可以包含另一个称为operatore 的复选框级别,实际上我试图在复选框输入的“on.change”方法中执行类似的操作

var config = [];
$(".nav").on("change", "input[type='checkbox']", function () {


    var selezione = {
        cassa: [{
            operatore: []
        }]
    };

    $(".check-negozio").each(function () {
        if (this.checked || this.indeterminate) {
            const npv = $(this).attr('data-npv');
            if (npv != null)
                selezione.negozio = npv;
            $(".check-cassa").each(function () {
                if (this.checked || this.indeterminate) {
                    const cs = $(this).attr('data-cs');
                    if (cs != null)
                        selezione.cassa.push({ CS: cs });
                    $(".check-operatore").each(function () {
                        if (this.chedked) {
                            const op = $(this).attr('data-op');
                            if (op != null)
                                selezione.cassa.operatore.push({ OP: op });
                        }
                    })
                }
            })
        }
    })

    config.push(selezione);
    console.log(config)
    //$.post("api/prodotti/post/", config);
});

问题在于,使用以下方法,operatore 和 CS 处于不同的级别,因此对象如下所示:[{ cassa: [{ CS: 1 }, { operatore: [] }], negozio: "0" }]何时应该[{ cassa: [{ CS: 1, operatore: [] }], negozio: "0" }]

这是一个带有 HTML 和 JS 代码的实时示例的JSFiddle

标签: javascriptjquerymultidimensional-arraycheckbox

解决方案


根据上面的代码,您CS先将对象推送到数组中,然后再将operatore对象推送到cassa数组中。相反,您可以尝试同时准备好CSoperatore值,然后将它们绑定到一个对象中并推入cassa.Something 像这样:

selezione.cassa.push({ CS: cs , operatore: op });

推荐阅读