javascript - 依赖元素结构化数组的层次树
问题描述
我正在寻找一种有效的方法来从 JavaScript 中的以下数据结构构建树。每个条目的长度始终为 5,并且条目之间永远不存在任何间隙(即空值)。
var geographies = [
[ 'Denmark', 'Midtjylland', null, null, null ],
[ 'Denmark', 'Syddanmark', 'Langeland', null, null ],
[ 'Denmark', 'Syddanmark', 'Ærø', null, null ],
[ 'Japan', 'Okinawa', 'Izenajima', null, null ],
[ 'Japan', 'Hokkaido', 'Rishiri', 'Rishiri-to', null ]
]
所需的输出应如下所示:
[{
label: "Denmark",
children: [{
label: "Midtjylland",
},
{
label: "Syddanmark",
children: [{
label: "Langeland"
},
{
label: "Ærø"
}]
}
]
}, {
label: "Japan",
children: [{
label: "Okinawa",
children: [{
label: "Izenajima"
}]
}, {
label: "Hokkaido",
children: [{
label: "Rishiri",
children: [{
label: 'Rishiri-to'
}]
}]
}]
}]
解决方案
您可以在每个子数组的第一个元素上对数组进行to_tree
分组,如果它们不为空,则调用分组数组:
function to_tree(d){
var c = {}
for (var i of d){
var k = i.shift();
c[k] = k in c ? [...c[k], i] : [i]
}
return Object.keys(c).map(function(x){return {label:x, ...(c[x].filter(j => j.length).length ? {children:to_tree(c[x].filter(j => j.length))} : {})}})
}
var geographies = [[ 'Denmark', 'Midtjylland', null, null, null ], [ 'Denmark', 'Syddanmark', 'Langeland', null, null ], [ 'Denmark', 'Syddanmark', 'Ærø', null, null ], [ 'Japan', 'Okinawa', 'Izenajima', null, null ], [ 'Japan', 'Hokkaido', 'Rishiri', 'Rishiri-to', null ]]
var geographies1 = [[ 'Greece', null, null, null, null ], [ 'Greece', 'Ionian Islands', 'Lefkada', null, null ], [ 'Greece', 'Attica', 'Salamis', null, null ], [ 'Greece', 'Ionian Islands', 'Cephalonia', null, null ], [ 'Greece', 'Thessaly', 'Skiathos', null, null ], [ 'Greece', 'South Aegean', 'Kea', null, null ], [ 'Greece', 'Attica', 'Kythira', null, null ]]
var r = to_tree(geographies.map(x => x.filter(y => y != null)));
var r1 = to_tree(geographies1.map(x => x.filter(y => y != null)));
console.log(r)
console.log(r1)
输出:
[
{
"label": "Denmark",
"children": [
{
"label": "Midtjylland"
},
{
"label": "Syddanmark",
"children": [
{
"label": "Langeland"
},
{
"label": "Ærø"
}
]
}
]
},
{
"label": "Japan",
"children": [
{
"label": "Okinawa",
"children": [
{
"label": "Izenajima"
}
]
},
{
"label": "Hokkaido",
"children": [
{
"label": "Rishiri",
"children": [
{
"label": "Rishiri-to"
}
]
}
]
}
]
}
]
[
{
"label": "Greece",
"children": [
{
"label": "Ionian Islands",
"children": [
{
"label": "Lefkada"
},
{
"label": "Cephalonia"
}
]
},
{
"label": "Attica",
"children": [
{
"label": "Salamis"
},
{
"label": "Kythira"
}
]
},
{
"label": "Thessaly",
"children": [
{
"label": "Skiathos"
}
]
},
{
"label": "South Aegean",
"children": [
{
"label": "Kea"
}
]
}
]
}
]
推荐阅读
- javascript - 对象数组,返回特定键的值
- bash - 在bash中,我的代码中有重叠的引号,不允许再次包装整个引号
- python - 你能限制每个用户 Django 的记录数吗
- python - 为什么索引值会发生变化?
- python - 使用我的程序的每个人都必须看到它旁边的丑陋代码吗?
- java - bytebuddy - 堆栈操作按名称而不是偏移量加载/存储变量
- javascript - 改变 translateX() 转换方向的 ReactJS 问题
- unit-testing - 为什么 Mocha & Chia 单元测试未能在 Web 组件构造函数中捕获预期错误?
- segmentation-fault - MPI_Init() 在带有 MPICH 安装的 Raspberry Pi4 上崩溃
- r - 如何在 Linux 上安装 nloptr