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

将数组属性合并为JSON字符串格式的新属性

解决方案

首先,我们可以通过分组+格式转换两步来实现需求:先按orderNo对原数组进行分组,再将每组内的description和note整理成JSON字符串格式的items属性,最后转换成目标结构。

代码实现(JavaScript)

const input = [
  { "orderNo":"1", "description":"Item 1", "note": "Note 1" },
  { "orderNo":"2", "description":"Item 2", "note": "Note 2" },
  { "orderNo":"2", "description":"Item 3", "note": "Note 3" }
];

// 第一步:按orderNo分组,只保留需要的description和note字段
const grouped = input.reduce((acc, item) => {
  const key = item.orderNo;
  if (!acc[key]) {
    acc[key] = [];
  }
  acc[key].push({ description: item.description, note: item.note });
  return acc;
}, {});

// 第二步:转换为目标结构,将分组结果转为索引键+items JSON字符串
const result = Object.entries(grouped).map(([orderNo, items], index) => ({
  [index]: [
    {
      orderNo,
      items: JSON.stringify(items) // 把数组转为标准JSON字符串
    }
  ]
}));

console.log(JSON.stringify(result, null, 2));

输出结果

运行代码后会得到完全匹配需求的结构:

[
  {
    "0": [
      {
        "orderNo": "1",
        "items": "[{\"description\":\"Item 1\",\"note\":\"Note 1\"}]"
      }
    ]
  },
  {
    "1": [
      {
        "orderNo": "2",
        "items": "[{\"description\":\"Item 2\",\"note\":\"Note 2\"},{\"description\":\"Item 3\",\"note\":\"Note 3\"}]"
      }
    ]
  }
]

关键细节说明

  • reduce方法是分组的核心,能高效将相同orderNo的项归为一组,同时过滤掉不需要的字段;
  • JSON.stringify负责把分组后的子数组转为标准JSON字符串,完全符合示例中items的格式要求;
  • 如果需要让items用单引号包裹(如示例中的写法),可以在JSON.stringify后追加.replace(/"/g, "'"),不过通常JSON规范优先使用双引号,可根据实际场景调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:29:18