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

103
Views
Build JSON Tree from Array using node string

I am following the example from this link Build tree array from JSON in JavaScript to generate my desired tree output. What I wanted to do was to make the "name" property value as the property name itself and remove the code property from the result. I tried to play with it but I have a little knowledge on how it works.

Codepen Link: json tree

Here is my desired result:

[
    {
        "one": "default value",
        "children": [
            {
                "one one": "default value"
            },
            {
                "one two": "default value"
            }
        ]
    },
    {
        "two": "default value"
    },
    {
        "three": "default value"
    }
]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Instead of using

el

build a new object with a computed property name and take the reference of map[el.code] later in

map[parent].children.push(map[el.code]);

const
    arr = [{ code: "1", name: "one" }, { code: "1.1", name: "one one" }, { code: "1.2", name: "one two" }, { code: "2", name: "two" }, { code: "3", name: "three" }],
    transformToTree = (arr, root = '') => {
         let map = {}, last = [root], level = 0;
         map[root] = {};
         arr.forEach(el => {
              let parent = root;
              while (level && last[level].length >= el.code.length) level--;
              parent = last[level];
              level++;
              last.length = level;
              last.push(el.code);
              map[el.code] = { [el.name]: 'default value' };
              map[parent].children = map[parent].children || [];
              map[parent].children.push(map[el.code]);
         });
         return map[root].children;
    };    
console.log(transformToTree(arr));
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report
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!