Transforming object data to array for d3plus-react

80 Views Asked by At

I have an api that returns data in the following format:

{
    "Information Technology": {
        "Name": "Information Technology",
        "Change": "0.82%"
    },
    "Consumer Staples": {
        "Name": "Consumer Staples",
        "Change": "0.19%"
    }
}

I want to convert it to the following format inside my d3plus visualizations:

[
    {
        "Name": "Information Technology",
        "Change": "0.82%"
    },
    {
        "Name": "Consumer Staples",
        "Change": "0.19%"
    }
]

How do I do this. Here's my React component that uses d3plus:

function Chart() {
    const methods = {
        groupBy: 'Name',
        data: 'https://example.com/api/sectors-performance',
        size: d => d.Change
    };

    return <Treemap config={methods} />;
}
1

There are 1 best solutions below

0
Naresh On

There was a small hint in the docs which helped me come up with this solution:

function Chart() {
    const methods = {
        groupBy: 'id',
        data: 'https://example.com/api/sectors-performance',
        size: d => d.value
    };

    const formatter = d =>
        Object.keys(d).map(key => ({
            id: d[key].Name,
            value: numeral(d[key].Change).value()
        }));

    return <Treemap config={methods} dataFormat={formatter} />;
}

The trick is to send a formatter as a property!