如何从嵌套复选框中获取对象数组中的值?



在我的网站中,我有一个从 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" }]

这是一个JSFiddle,其中包含HTML和JS代码的实时示例

根据上面的代码,您首先将对象推送CS然后将对象推送operatorecassa数组中。相反,您可以尝试准备好CS值和operatore值,然后将它们绑定到单个对象中并推送到cassa。像这样:

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

最新更新