1

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"
    }
]

1 Answer 1

1

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; }

Sign up to request clarification or add additional context in comments.

2 Comments

That was what I did but it did not include the children.
@Dekso, please see edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.