function buildTree(arr, parentId = null) { let tree = []; for (let i = 0; i < arr.length; i++) { let item = arr[i]; if (item.parentId === parentId) { let children = buildTree(arr, item.id); if (children.length) { item.children = children; } tree.push(item); } } return tree; }