简体   繁体   中英

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? 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.

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM