Answer the question
In order to leave comments, you need to log in
How to mark child elements when building a tree based on an array of an object?
There is an array
const data = [
{
id: 1122031,
title: "Banner",
children: [
{
id: 1122032,
title: "prod 1"
},
{
id: 1122033,
title: "prod 2"
},
{
id: 1122034,
title: "prod 3"
},
{
id: 1366085,
title: "prod 6",
children: [
{
id: 1362085,
title: "prod 16"
}
]
}
]
}
];
function createTree(data, defaultId) {
const ul = document.createElement("ul");
data.map((item, index) => {
const li = document.createElement("li");
li.textContent = item.id;
if (item.children) {
li.appendChild(createTree(item.children, index));
}
ul.appendChild(li);
});
return ul;
}
<ul>
<li>
children
<ul>
<li>
0_children
<ul>
<li>0_children_0</li>
<li>0_children_1</li>
<li>0_children_2</li>
<li>
0_children_3
<ul>
<li>
0_children_3_children_0
</li>
<li>
0_children_3_children_1
</li>
</ul>
</li>
</ul>
</li>
<li>
1_children
</li>
</ul>
</li>
</ul>
Answer the question
In order to leave comments, you need to log in
Let the second parameter be an array of indices, empty by default (respectively, when you call the function yourself, you don't need to pass it). At the beginning of processing a data element, put its index into an array, after processing, remove it. Well, the text - collect from the array what you need:
function createTree(data, index = []) {
const ul = document.createElement('ul');
data.forEach((n, i) => {
index.push(i);
const li = document.createElement('li');
li.textContent = index.join('_');
if (n.children) {
li.appendChild(createTree(n.children, index));
}
ul.appendChild(li);
index.pop();
});
return ul;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question