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
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; }
answered Mar 3, 2022 at 8:43
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Dekso
That was what I did but it did not include the children.
Nina Scholz
@Dekso, please see edit.
lang-js