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

如何匹配JSON对象中totalById与nameById的ID并生成指定格式数据?

匹配ID生成目标对象集合

原始数据

const attrs = {
  daily: {
    "totalById": {
      "6137ad545fc0c40785920e48": 0,
      "612e64f65fc0c4078569bacf": 0,
      "614231535fc0c40785bf0907": 20
    }
  },
  "nameById": {
    "6137ad545fc0c40785920e48": "Automation",
    "612e64f65fc0c4078569bacf": "Excellent Idea",
    "614231535fc0c40785bf0907": "Beginning ",
  }
};

需求

通过匹配totalById和nameById中的ID,生成包含name和total字段的对象集合,示例格式如下:

{name: "Beginning", total: 20}, {name: "Automation", total: 0}

解决方法

不需要刻意对齐两个对象的键顺序,直接通过ID关联取值即可:

  1. 先提取两个目标对象的引用:
const totalMap = attrs.daily.totalById;
const nameMap = attrs.nameById;
  1. 遍历totalById的所有ID,通过ID从nameById中取出对应名称,组合成目标对象:
const result = Object.keys(totalMap).map(id => ({
  name: nameMap[id].trim(), // 去除名称末尾多余空格
  total: totalMap[id]
}));
  1. 若需要过滤掉total为0的项(可选),可以在map前加filter:
const filteredResult = Object.keys(totalMap)
  .filter(id => totalMap[id] !== 0)
  .map(id => ({
    name: nameMap[id].trim(),
    total: totalMap[id]
  }));

输出结果

  • 完整结果:
[
  { name: "Automation", total: 0 },
  { name: "Excellent Idea", total: 0 },
  { name: "Beginning", total: 20 }
]
  • 过滤后结果(仅保留total≠0的项):
[
  { name: "Beginning", total: 20 }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:25:35