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

如何用JavaScript将JSON响应映射为去重的层级结构数组

解决字符串数组转层级去重结构问题

你提到想用map()实现需求,但map()是一对一的转换逻辑,这里需要聚合数据并去重,用reduce()会更合适。另外你给出的目标结构存在语法问题——数组中不能包含键值对,应该将Category对应的值改为对象;同时重复的Item可以借助Set自动完成去重。

实现代码

const ctiResponse = [
    "Category / Type1 / Item1",
    "Category / Type1 / Item2",
    "Category / Type1 / Item2",
    "Category / Type1 / Item3",
    "Category / Type2 / Item1",
    "Category / Type2 / Item2",
    "Category / Type2 / Item2",
    "Category / Type2 / Item3",
    "Category / Type3 / Item1",
    "Category / Type3 / Item2",
    "Category / Type3 / Item2",
    "Category / Type3 / Item3",
];

// 用reduce聚合数据并去重
const result = ctiResponse.reduce((acc, str) => {
    // 分割字符串并去除各部分空格
    const [category, type, item] = str.split(' / ').map(part => part.trim());
    
    // 初始化分类对象
    if (!acc[category]) {
        acc[category] = {};
    }
    // 初始化类型对应的Set(自动去重)
    if (!acc[category][type]) {
        acc[category][type] = new Set();
    }
    // 添加Item到Set
    acc[category][type].add(item);
    
    return acc;
}, {});

// 将Set转换为数组,生成最终结构
const ctis = [
    Object.fromEntries(
        Object.entries(result).map(([cat, types]) => [
            cat,
            Object.fromEntries(
                Object.entries(types).map(([type, items]) => [type, Array.from(items)])
            )
        ])
    )
];

console.log(ctis);

最终输出结构

[
    {
        "Category": {
            "Type1": ["Item1", "Item2", "Item3"],
            "Type2": ["Item1", "Item2", "Item3"],
            "Type3": ["Item1", "Item2", "Item3"]
        }
    }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:21:37