list to tree
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let tree = [
{ id: 1, parentId: null, name: 'a' },
{ id: 2, parentId: null, name: 'b' },
{ id: 3, parentId: 1, name: 'c' },
{ id: 4, parentId: 2, name: 'd' },
{ id: 5, parentId: 1, name: 'e' },
{ id: 6, parentId: 3, name: 'f' },
{ id: 7, parentId: 4, name: 'g' },
{ id: 8, parentId: 7, name: 'h' },
]
const copy = JSON.parse(JSON.stringify(tree))
function listToTree(list){
list.forEach(parent => {
list.forEach(child => {
if(parent.id === child.parentId) {
if(!parent.children) {
parent.children = []
}
parent.children.push(child)
}
})
})
list = list.filter(item => item.parentId === null)
return list
}
const result = listToTree(copy)
console.log(result);
console.log(JSON.stringify(result));
</script>
</body>
</html>
tree to list
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const tree = [{ "id": 1, "parentId": null, "name": "a", "children": [{ "id": 3, "parentId": 1, "name": "c", "children": [{ "id": 6, "parentId": 3, "name": "f" }] }, { "id": 5, "parentId": 1, "name": "e" }] }, { "id": 2, "parentId": null, "name": "b", "children": [{ "id": 4, "parentId": 2, "name": "d", "children": [{ "id": 7, "parentId": 4, "name": "g", "children": [{ "id": 8, "parentId": 7, "name": "h" }] }] }] }]
function treeToArr(arr, result=[]) {
for(let i = 0;i < arr.length; i++) {
const obj = arr[i]
const copy = JSON.parse(JSON.stringify(obj))
delete obj.children
result.push(obj)
if(copy.children) {
treeToArr(copy.children, result)
}
}
return result
}
const arr = treeToArr(tree)
console.log(JSON.stringify(arr));
console.log(arr)
</script>
</body>
</html>