Search code examples
javascriptreactjsreact-d3

How to translate object data to a format known by react-d3-tree


I am currently having problems using my data in react-d3-tree. The data coming from the server is not compatible with the format that react-d3-tree accepts.

I was told that doing the process using a foreach function for every item will work, but I think that will be really slow, especially whe the data is too big.

The data (as shown in my console) right now is like this:

0:  {
        series: 'Fate'
        type: 'Servant'
        class: 'Saber',
    },
1:  {
        series: 'Fate',
        type: 'Servant'
        class: 'Archer',
    },
2:  {
        series: 'Fate',
        type: 'Demi-servant'
        class: 'Shielder',
    }

And I want to achieve this structure:

[
    {
        name: 'Fate',
        children: [
            {
                name: 'Servant',
                children: [
                    {
                        name: 'Saber',
                        children: []
                    },
                    {
                        name: 'Archer',
                        children: []
                    }
                ]
            },
            {
                name: 'Demi-servant',
                children: [
                    {
                        name: 'Shielder',
                        children: []
                    }
                ]
            }
        ]
    }
]

This is only sample data, and later on, and I might be converting data with more children. Is there any npm package that can be helpful?


Solution

  • Nevermind, I actually found my answer.

    I'll share these useful links in case anyone finds this question too.

    https://www.npmjs.com/package/shape-json
    https://www.npmjs.com/package/shape-array