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

VueJS如何提取表格勾选行数据生成指定格式的字典列表

问题原因

  • 你调用reduce时初始值设置为了空对象{},所以最终只会返回单个对象,无法得到数组结构
  • 键名赋值逻辑错误,你把行数据的id/typ等属性值当成了键名,不符合你需要的键名格式

最优解决方案(更适合新手的map写法)

你已经先过滤出了勾选的行,直接用map遍历生成对应结构的对象即可,逻辑更直观:

putInvalidsRef() {
  // 过滤出勾选的行
  const selectedRef = this.rowsInvalidsRef.filter(ref => ref.isSelected)
  // 遍历生成目标结构数组
  const refsDicts = selectedRef.map((item, index) => {
    // 序号从1开始,对应你示例的id1/type1格式
    const idx = index + 1
    return {
      [`id${idx}`]: item.newID || null,
      [`type${idx}`]: item.newType || null,
      [`url${idx}`]: item.newURL || null,
      [`exp${idx}`]: item.newExpDate || null
    }
  })
  console.log(refsDicts)
  this.$http.admin.putInvalidsRef(refsDicts)
    .then(getInvalidsRef)
}

如果你的后端实际需要每个对象的键名是固定的id/type/url/exp(示例里的序号只是你标注用),把return里的键名改成固定字符串即可:

return {
  id: item.newID || null,
  type: item.newType || null,
  url: item.newURL || null,
  exp: item.newExpDate || null
}

reduce实现的修正写法

如果一定要用reduce实现,把初始值改成空数组,每次把生成的行对象push进累加数组:

const refsDicts = selectedRef.reduce((acc, item, index) => {
  const idx = index + 1
  acc.push({
    [`id${idx}`]: item.newID || null,
    [`type${idx}`]: item.newType || null,
    [`url${idx}`]: item.newURL || null,
    [`exp${idx}`]: item.newExpDate || null
  })
  return acc
}, [])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:24:04