这种数据结构怎么构造树结构?
数据结构是这样的 text
是文本,没规律 value
的规律是第一层级 2 个字符串,第二层级 4 个,前 2 个是第一层级 value
值,以此类推。
const data = [
{text:'节点1',value:'01'},
{text:'节点2',value:'02'},
{text:'节点1-1',value:'0101'},
{text:'节点1-2',value:'0102'},
{text:'节点1-3',value:'0103'},
{text:'节点2-1',value:'0201'},
{text:'节点1-1-1',value:'010101'},
{text:'节点1-1-2',value:'010102'},
{text:'节点1-2-1',value:'010201'},
]
期望的树结构,并保证节点的顺序跟原数据保持一致:
const result = [
{
title: '节点1',
key: '01',
children: [
{
title: '节点1-1',
key: '0101',
children: [
{
title: '节点1-1-1',
key: '010101',
},
{
title: '节点1-1-2',
key: '010102',
},
]
}, {
title: '节点1-2',
key: '0102',
children: [
{
title: '节点1-2-1',
key: '010201',
},
]
}, {
title: '节点1-3',
key: '0103',
},
]
},
{
title: '节点2',
key: '02',
children: [
{
title: '节点2-1',
key: '0201',
},
]
},
]
回复
1个回答

test
2024-06-28
function buildTree(data) {
const map = {};
const result = [];
data.forEach(item => {
const node = {
title: item.text,
key: item.value,
children: []
};
map[item.value] = node;
const parentValue = item.value.slice(0, -2);
if (parentValue) {
map[parentValue].children.push(node);
} else {
result.push(node);
}
});
function cleanChildren(node) {
if (node.children.length === 0) {
delete node.children;
} else {
node.children.forEach(child => cleanChildren(child));
}
}
result.forEach(node => cleanChildren(node));
return result;
}
const data = [
{text:'节点1', value:'01'},
{text:'节点2', value:'02'},
{text:'节点1-1', value:'0101'},
{text:'节点1-2', value:'0102'},
{text:'节点1-3', value:'0103'},
{text:'节点2-1', value:'0201'},
{text:'节点1-1-1', value:'010101'},
{text:'节点1-1-2', value:'010102'},
{text:'节点1-2-1', value:'010201'},
];
const result = buildTree(data);
console.log(result);
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容