We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
/* *数组:[{id:1, parentId: 0}, {id:2, parentId:1},{id:3, parentId:1}] *输出结果:[{id:1, parentId: 0,children:[{id:2, parentId:1},{id:3, parentId:1}]}] *说明:parentId为0 的是根节点 */
The text was updated successfully, but these errors were encountered:
Sorry, something went wrong.
var arr = [{ id: 1, parentId: 0 }, { id: 2, parentId: 1 }, { id: 3, parentId: 1 }] function buildTree(arr) { const result = [] const copyArr = [...arr] const map = {} copyArr.forEach((item) => { map[item.id] = item }) for (const key in map) { const item = map[key] if (item.parentId === 0) { result.push(item) } else { const parent = map[item.parentId] parent.children = parent.children || [] parent.children.push(item) } } return result } buildTree(arr)
function fn(arr) { let parents = [] const len = arr.length for (let i = 0; i < len; i++) { parents[arr[i].id] = arr[i] } let parent for (let i = 0; i < arr.length; i++) { parent = parents[arr[i].parentId] if (!parent) continue if (parent.children) { parent.children.push(arr[i]) } else { parent.children = [arr[i]] } arr.splice(i, 1) i-- } return arr }
No branches or pull requests
The text was updated successfully, but these errors were encountered: