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

如何将对象格式数据转为数组适配d3plus-react可视化?

Solution for Converting API Response Format for d3plus Treemap

Hey there! Let's get your data formatted correctly for the d3plus Treemap component—this is a quick fix with JavaScript's built-in methods and React's state management.

Step 1: The Core Data Transformation

Your API returns an object where each key is a sector name, and the value is the corresponding sector data object. To turn this into the array format d3plus expects, we can use Object.values()—this method grabs all the value objects from your API response and wraps them into an array, which is exactly the structure you need.

Step 2: Update Your React Component

Instead of passing the API URL directly to the data property, we'll fetch the data ourselves, transform it, and then feed the processed array to the Treemap. Here's the revised code:

import { useState, useEffect } from 'react';
import { Treemap } from 'd3plus-react';

function Chart() { 
  const [sectorData, setSectorData] = useState([]);

  useEffect(() => {
    // Fetch and process the API data
    fetch('https://example.com/api/sectors-performance')
      .then(response => response.json())
      .then(rawApiData => {
        // Convert the object to the required array format
        const formattedData = Object.values(rawApiData);
        setSectorData(formattedData);
      })
      .catch(error => {
        console.error('Failed to load or process data:', error);
        // Add error handling here if needed (e.g., show a user-friendly message)
      });
  }, []);

  const treemapConfig = { 
    groupBy: 'Name', 
    data: sectorData,
    size: d => d.Change 
  }; 

  return <Treemap config={treemapConfig} />; 
}

export default Chart;

Key Changes Explained

  • Added useState to store the processed array of sector data
  • Used useEffect to fetch the API data once when the component mounts
  • Object.values(rawApiData) handles the conversion from your API's object structure to the array format d3plus requires
  • Pass the processed sectorData to the Treemap instead of the raw API URL

This ensures d3plus receives the data in the structure it needs to render the treemap properly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:54:44