本文介绍了您如何将代表层次结构的一组数组合并到实际层次结构中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从数据源创建一个分层的界面,该界面将信息作为表示级别的单独数组提供。
I am trying to create a hierarchical interface form a datasource that provides the information as separate arrays that represent levels.
我只是在寻找一些灵感或想法关于如何解决这个问题。我尝试了一些没有成功的事情。
I'm just looking for some inspiration or ideas on how to approach this problem. I've tried a few things with no success.
源:
[
[{id:1}, {id:2}, {id:3}],
[{id:1}, {id:2}, {id:4}],
[{id:5}, {id:6}],
[{id:5}, {id:7}, {id:8}]
]
所需结果:
[
{
"id":1,
"children": [
{
"id": 2,
"children": [
{
"id": 3
},
{
"id": 4
}
]
}
]
},{
"id": 5,
"children": [
{
"id": 6
},
{
"id": 7,
"children": [
{
"id": 8
}
]
}
]
}
]
推荐答案
下面是一个功能性的两步过程,首先将其转换为以下格式:
Here's a functional two-step process that first converts it to this format:
// this isn't even my final form(at)!
{
1: {
2: {
3: {},
4: {}
}
},
5: {
6: {},
7: {
8: {}
}
}
}
,然后将其转换为最终格式:
and then converts that to the final format:
function hierarchy (paths) {
const root = paths.reduce(
(root, nodes) => (
nodes.reduce(
(root, { id }) => root[id] = root[id] || {}, root
), root
), {}
);
return function recurse (root) {
return Object.entries(root).reduce((root, [id, dir]) => {
const children = recurse(dir);
root.push(Object.assign({ id }, children.length > 0 ? { children } : {}));
return root;
}, []);
}(root);
}
let source = [
[{id:1}, {id:2}, {id:3}],
[{id:1}, {id:2}, {id:4}],
[{id:5}, {id:6}],
[{id:5}, {id:7}, {id:8}]
];
console.log(hierarchy(source));
这篇关于您如何将代表层次结构的一组数组合并到实际层次结构中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!