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

