You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

技术求助:实现扁平数据到三级层级结构的转换(升级现有二级转换方案)

实现三级层级数据转换方案

我来帮你把现有二级结构的转换逻辑升级成三级(category → brand → 产品项)的结构,其实只需要在原来的reduce逻辑里增加一层品牌的分组即可,下面是具体的实现思路和代码:

修改后的转换代码

// 第一步:用reduce构建嵌套的分组结构
const groupedData = sfdata.data.reduce((acc, { items: [cat, brandName, productName, salesTY, salesLY, unitsTY, unitsLY] }) => {
  // 确保当前category存在,不存在则初始化
  acc[cat] = acc[cat] || {};
  // 确保当前category下的brand存在,不存在则初始化产品数组
  acc[cat][brandName] = acc[cat][brandName] || [];
  // 将产品项推入对应brand的数组
  acc[cat][brandName].push({
    name: productName,
    salesTY,
    salesLY,
    unitsTY,
    unitsLY
  });
  return acc;
}, {});

// 第二步:将嵌套对象转换为期望的数组结构
const chartdata = Object.entries(groupedData).map(([category, brands]) => ({
  category,
  children: Object.entries(brands).map(([brand, products]) => ({
    brand,
    children: products
  }))
}));

代码逻辑说明

和你原来的二级转换逻辑相比,核心变化是:

  • 原来的acc[cat]是直接存储产品数组,现在改成存储品牌为key、产品数组为value的对象
  • 最后转换结构时,多了一层Object.entries(brands)的映射,把品牌对象转成{brand: "...", children: [...]}的结构

输入输出示例验证

输入数据片段

[
  { "items": [ "SSD", "PBNA", "MOUNTAIN DEW", 851255.3500000001, 672407.8399999997, 782364.9999999991, 641579.0000000006 ], "hints": { "index": 0 } },
  { "items": [ "Energy", "RED BULL NORTH AMERICA", "RED BULL", 836632.2299999997, 654021.2899999995, 267216, 214321.00000000015 ], "hints": { "index": 1 } },
  { "items": [ "SSD", "PBNA", "PEPSI", 478704.02999999974, 392746.69999999995, 533557.0000000006, 457008.0000000001 ], "hints": { "index": 4 } },
  { "items": [ "Energy", "RED BULL NORTH AMERICA", "RED BULL EDITIONS", 449618.55000000016, 328150.8999999997, 162428.9999999999, 117521.00000000001 ], "hints": { "index": 5 } },
  { "items": [ "SSD", "CCNA", "COKE", 349685.7899999996, 276766.95, 445485.0000000002, 351214.0000000003 ], "hints": { "index": 9 } }
]

输出结果(符合你的期望结构)

[
  { "category": "SSD", "children": [
    { "brand": "PBNA", "children": [
      { "name": "MOUNTAIN DEW", "salesTY": 851255.3500000001, "salesLY": 672407.8399999997, "unitsTY": 782364.9999999991, "unitsLY": 641579.0000000006 },
      { "name": "PEPSI", "salesTY": 478704.02999999974, "salesLY": 392746.69999999995, "unitsTY": 533557.0000000006, "unitsLY": 457008.0000000001 }
    ] },
    { "brand": "CCNA", "children": [
      { "name": "COKE", "salesTY": 349685.7899999996, "salesLY": 276766.95, "unitsTY": 445485.0000000002, "unitsLY": 351214.0000000003 }
    ] }
  ] },
  { "category": "Energy", "children": [
    { "brand": "RED BULL NORTH AMERICA", "children": [
      { "name": "RED BULL", "salesTY": 836632.2299999997, "salesLY": 654021.2899999995, "unitsTY": 267216, "unitsLY": 214321.00000000015 },
      { "name": "RED BULL EDITIONS", "salesTY": 449618.55000000016, "salesLY": 328150.8999999997, "unitsTY": 162428.9999999999, "unitsLY": 117521.00000000001 }
    ] }
  ] }
]

这个方案是在你原有代码的基础上扩展的,逻辑清晰且和原来的代码风格保持一致,也完全满足你需要的三级层级结构需求。

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

火山引擎 最新活动