Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
d3js v7 convert array into hierarchy

I have data formatted as below

[['x',2,3,'a'],['x',2,4,'b'],['y',1,3,'a']]

I want to convert it into something like below

{
  'name': 'top level',
  'children':
    [
      {
        'name': 'x',
        'children':
          [
            {
              'name': 2,
              'children':
                [
                  {
                    'name': 3,
                    'children':
                      [
                        {
                          'name': 'a',
                          'children': []
                        }
                      ]
                  },
                  {
                    'name': 4,
                    'children':
                      [
                        {
                          'name': 'b',
                          'children': []
                        }
                      ]
                  }
                ]
            }
          ]
      },
      {
        'name': 'y',
        'children':
          [
            {
              'name': 1,
              'children':
                [
                  {
                    'name': 3,
                    'children':
                      [
                        {
                          'name': 'a',
                          'children': []
                        }
                      ]
                  }
                ]
            }
          ]
      }
    ]
}

I want to graph the data into a clickable tidy tree.

I couldn't use d3.nest since it was already deprecated and I have no idea how to do it with vanilla javascript. Any help is appreciated.

Edit: based on pointers from @Andrei Savin I tried to run the following code. the problem is my array doesn't change, why?

let sampleInput = [['x',2,3,'a'],['x',2,4,'b'],['y',1,3,'a']];
let result = [];
let level = { result };

sampleInput.forEach(b => {
  b.forEach(c => {
    c.toString().split('/').reduce((d,e)=>{
      if(!d[e]){
        d[e] = {result:[]};
        d.result.push({e,'children':d[e].result});
      }

      return d[e];
    },level);
  })
});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!