<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let arr = [
{ id: 1, pid: 100, name: "A" },
{ id: 2, pid: 1, name: "B" },
{ id: 3, pid: 1, name: "C" },
];
function arrayToList(arr) {
const map = new Map();
const result = [];
arr.forEach((item) => {
map[item.id] = { ...item, children: [] };
});
arr.forEach((item) => {
const node = map[item.id];
if (!map[item.pid]) {
result.push(node);
} else {
map[item.pid].children.push(node);
}
});
return result;
}
console.log(arrayToList(arr));
</script>
</body>
</html>