You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery将两个等长数组按行合并?

解决两个等长数组按元素合并的问题

你的问题出在merge变量的逻辑里:遍历复选框时直接取el.value,但这个值是复选框自身的value,并非对应位置数量输入框的值,所以合并结果不符合预期。

下面是两种可行的解决方法:

方法一:基于已生成的两个数组合并

利用两个数组等长的特性,通过索引将对应位置的对象属性合并:

const ar1 = $('input[class=namecheckbox]').map((i, el) => ({id: el.id.slice(2)})).get();
const ar2 = $('.quantity_input').map((i, el) => ({quantity: el.value})).get();

// 合并逻辑
const merged = ar1.map((item, index) => ({
  ...item,
  ...ar2[index]
}));

console.log(merged);

方法二:一次遍历直接生成结果

避免生成两个中间数组,直接通过索引关联复选框和对应的数量输入框:

const checkboxes = $('input.namecheckbox');
const quantityInputs = $('.quantity_input');

const merged = checkboxes.map((i, el) => ({
  id: el.id.slice(2),
  quantity: quantityInputs.eq(i).val()
})).get();

console.log(merged);

两种方法最终都会得到每个元素包含id和对应quantity的数组,符合预期格式。

内容的提问来源于stack exchange,提问作者Henry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:22:05