如何用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
相关产品推荐
相关产品推荐

