javascript - 如何从嵌套复选框中获取对象数组中的值?
问题描述
在我的网站中,我有一个从 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
解决方案
根据上面的代码,您CS
先将对象推送到数组中,然后再将operatore
对象推送到cassa
数组中。相反,您可以尝试同时准备好CS
和operatore
值,然后将它们绑定到一个对象中并推入cassa
.Something 像这样:
selezione.cassa.push({ CS: cs , operatore: op });
推荐阅读
- php - 从 MySQL 显示数据到 PHP 页面问题
- c# - 在 IEnumerable 上使用 AsParallel - 它是否有任何并行性的好处?
- ruby-on-rails - 如何返回包含每个所有者名称的文件名数组的哈希?
- c - 在 C 中输入这个三角形的高度时打印帕斯卡三角形
- c++ - 等到请求完成 Qt
- javascript - p5.js 形状更新问题
- ios - 为什么我无法在 iOS 中使用 Chrome 浏览器发布到 Ant Media Server?
- node.js - 将 MongoDB Atlas 连接到 Heroku Node.js 应用程序的替代方案
- scala - 适用于 Play 2.6 和 Scala 2.12 的兼容 SBT 版本
- python - 为什么resample()后枚举多列时使用单括号不报错