将数组属性合并为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
相关产品推荐
相关产品推荐

