[英]Sorting an array with child - parent dependencies
I am given the following array of objects:我得到以下对象数组:
let data = [{id: 3, name: ''}, {id: 4, name: ''}, {id: 5, name: '', parent: 3}, {id: 6, name: '', parent: 5}, {id: 7, name: '', parent: 4}, {id: 8, name: '', parent: 8}];
How do I create a nested list, where an object with corresponding parent element is appended to a new <li>
element?如何创建一个嵌套列表,其中将具有相应父元素的 object 附加到新的
<li>
元素? So to make it clear it would look something like this:所以为了清楚起见,它看起来像这样:
<li>
object id:3 (parent)
<li>object id:5</li>(child)
</li>`
Any clues?有什么线索吗? :)
:)
You could do this with two functions one to create nested tree structure and another one to create a nested html structure based on previously create tree structure.您可以使用两个函数来执行此操作,一个用于创建嵌套树结构,另一个用于创建基于先前创建的树结构的嵌套 html 结构。
let data = [{id: 3, name: ''}, {id: 4, name: ''}, {id: 5, name: '', parent: 3}, {id: 6, name: '', parent: 5}, {id: 7, name: '', parent: 4}, {id: 8, name: '', parent: 8}]; const toTree = (data, pid = undefined) => { return data.reduce((r, e) => { if (pid == e.parent) { const obj = {...e } const children = toTree(data, e.id); if (children) obj.children = children r.push(obj) } return r }, []) } const toHtml = (data) => { const ul = document.createElement('ul') data.forEach(e => { const li = document.createElement('li'); const text = document.createElement('span') text.textContent = `object id: ${e.id}`; li.appendChild(text) const children = toHtml(e.children); if (children) li.appendChild(children) ul.appendChild(li) }) return ul } const tree = toTree(data) const html = toHtml(tree) document.body.appendChild(html)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.