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

JavaScript嵌套循环仅保留首个收件人信息问题求助

问题分析

你当前的核心问题是对象的键名不能重复:每次循环收件人时,都用同一个[t("inbox.recipient")]作为键赋值,后面的内容会直接覆盖前面的,所以最终只保留最后一个收件人。这和i18n无关,是数据结构设计的问题——你期望的JSON结构本身不合法,同一个对象里不允许存在重复键。

解决方案

方案1:将收件人存为数组(推荐)

把收件人字段改成数组,既能保留所有收件人信息,结构也符合JSON规范:

const resultsArray = [];
// 注意:原始results是对象而非数组,需先转成数组再遍历
Object.values(results).forEach(result => {
  const item = {
    [t("inbox.message")]: result?.message,
    // 初始化收件人数组
    [t("inbox.recipients")]: []
  };
  if (result?.recipients && !isEmpty(result.recipients)) {
    // 将所有收件人名字推入数组
    Object.values(result.recipients).forEach(recipient => {
      item[t("inbox.recipients")].push(recipient.name);
    });
  }
  resultsArray.push(item);
});

最终生成的合法结构:

{
  "(translated message_title)": "This is a message",
  "(translated recipients)": ["I'm a recipient", "I'm another recipient"]
}

方案2:给收件人键名加索引(不推荐,结构可读性差)

如果非要贴近你原本的期望,可以给每个收件人键名添加索引后缀,避免重复:

const resultsArray = [];
Object.values(results).forEach(result => {
  const item = {
    [t("inbox.message")]: result?.message
  };
  if (result?.recipients && !isEmpty(result.recipients)) {
    Object.values(result.recipients).forEach((recipient, idx) => {
      // 给键名添加索引后缀
      item[`${t("inbox.recipient")}_${idx}`] = recipient.name;
    });
  }
  resultsArray.push(item);
});

最终生成的结构:

{
  "(translated message_title)": "This is a message",
  "(translated recipient_name)_0": "I'm a recipient",
  "(translated recipient_name)_1": "I'm another recipient"
}
额外注意点
  • 原始results是键为0、1的对象,不是数组,不能直接调用forEach,需先用Object.values(results)转成数组再遍历。
  • 原代码中if (!isEmpty(result?.recipients))缺少闭合括号,需修正语法错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:20:34