[英]Objects with Array values into a tree
我有一个对象数组,其中每个对象都有一个值数组。 数据结构不是理想的,但这是我访问它的唯一方法。 我正在尝试将此结构转换为树形结构,以便构建一个D3缩进式可折叠表。
我已经尝试修改一些以前找到的答案,但尚未成功。 这是我正在研究的当前JSFiddle的链接。
http://jsfiddle.net/COLTstreet/fsve7w2L/25/
这是数据如何传给我的一个小例子。
{
"data": [
{
"items": [
"All Other",
"4C FOODS CORP"
],
"hints": {
"index": 0
}
},
{
"items": [
"All Other",
"PBNA"
],
"hints": {
"index": 14
}
},
{
"items": [
"All Other",
"PRIVATE LABEL"
],
"hints": {
"index": 15
}
},
{
"items": [
"Base Water",
"CCNA"
],
"hints": {
"index": 18
}
},
{
"items": [
"Base Water",
"CRYSTAL GEYSER"
],
"hints": {
"index": 19
}
}
]
}
我需要这样的代码来完成:
[
{
"Category": "All Other",
"children": [
{
"name": "4C FOODS CORP"
},
{
"name": "PBNA"
},
{
"name": "PRIVATE LABEL"
}
]
},
{
"Category": "Base Water",
"children": [
{
"name": "CCNA"
},
{
"name": "CRYSTAL GEYSER"
}
]
}
]
一种解决方案是首先将Array.reduce()与解构结合使用,以生成用于按类别对元素进行分组的object
,然后在第二步中,对生成的对象entries
使用Array.map()以获得所需的输出:
const input = { "data": [ {"items": ["All Other", "4C FOODS CORP"], "hints": {"index": 0}}, {"items": ["All Other", "PBNA"], "hints": {"index": 14}}, {"items": ["All Other", "PRIVATE LABEL"], "hints": {"index": 15}}, {"items": ["Base Water", "CCNA"], "hints": {"index": 18}}, {"items": ["Base Water", "CRYSTAL GEYSER"], "hints": {"index": 19}} ] }; // Group by the category. let res = input.data.reduce((acc, {items: [cat, val]}) => { acc[cat] = acc[cat] || []; acc[cat].push({name: val}); return acc; }, {}); // Generate desired output structure. res = Object.entries(res).map(([k, v]) => ({category: k, children: v})); console.log(res);
.as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.