web123456

js implementation - convert tiled data into tree structure

// Tile data const list = [ { id: 1, pid: 0, name: 'one'}, { id: 2, pid: 1, name: 'two'}, { id: 3, pid: 1, name: 'three'}, { id: 4, pid: 2, name: 'four'}, ] // The following conversion const deleteIds = [] list.forEach((i) => { i.children = [] list.forEach((item) => { // Determine whether there is a parent (there are: push it into the parent's children and push the id into the id to be deleted) if (item.pid === i.id) { i.children.push(item) deleteIds.push(item.id) } }) // If children are empty, delete the children if (i.children.length === 0) { delete i.children } }) // Filter the id in deleteIds const result = list.filter(i => !deleteIds.includes(i.id)) console.log(list, result)