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

使用JavaScript/TypeScript遍历复杂JSON按组提取饼图数据的实现方法

问题原因

你当前的实现直接将所有data数组里的value逐项追加到plotValue数组末尾,没有按所属的plots分组,所以得到的是扁平化的一维数组。

实现代码

this.myData[0].detailed_statistics.forEach(value => {
  value.plots.forEach(val => {
    // 标题、半径单条对应一个分组,直接正常存储
    this.plotTitles.push(val.chart_title)
    this.plotRadius.push(val.radius)
    
    // 初始化当前分组的临时存储数组
    const currentValues = []
    const currentNames = []
    const currentColors = []
    val.data.forEach(plt => {
      currentValues.push(plt.value)
      currentNames.push(plt.plain_naming)
      currentColors.push(plt.hex_colour)
    })
    
    // 按需求处理后存入全局数组:单元素直接存值,多元素存数组
    this.plotValue.push(currentValues.length === 1 ? currentValues[0] : currentValues)
    this.plotPlainName.push(currentNames.length === 1 ? currentNames[0] : currentNames)
    this.plotColor.push(currentColors.length === 1 ? currentColors[0] : currentColors)
  })
})

运行后this.plotValue的输出就会和你期望的完全一致:
[['386', '504'], ['737', '54'], '53', '2', '51']

如果你后续要传给饼图组件的参数更适配统一数组格式,也可以去掉长度判断,哪怕单元素也存为数组,使用更方便:

this.plotValue.push([...currentValues])
this.plotPlainName.push([...currentNames])
this.plotColor.push([...currentColors])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:45:04