gpt4 book ai didi

javascript - 如何将数据表动态转换为树状json格式?

转载 作者:行者123 更新时间:2023-11-30 09:18:30 26 4
gpt4 key购买 nike

我正在使用此数据输入来创建 D3.js 可视化:

Tree Layout

好的,现在我的数据输入是一个我硬编码的 json 文件:

{
"name":"Fun",
"children": [
{
"name": "Legal",
"children": [
{ "name": "Adventure" },
{ "name": "Movie" },
{ "name": "M&m" }
]
},
{
"name": "frowned upon",
"children": [
{ "name": "recreational stuff" },
{ "name": "religious views" }
]
}
]
}

但我的数据输入实际上是:

Data table input

如何将这个数据表动态转换成上面提到的Json格式,是写一个函数解析数据表将它转换成上面的格式,还是有其他方法。

最佳答案

您可以编写递归函数来重组数据。

const a = [[
'fun', 'legal', 'adventure',
], [
'fun', 'legal', 'movie',
], [
'fun', 'legal', 'm&m'
], [
'fun', 'frowned upon', 'rec stuff'
], [
'fun', 'frowned upon', 'religius views'
]];

let t = [];

const addLeaf = (array) => {
if (!array || !array.length) return;

let temp = { name: array[0], children: [] };

if (array.length > 1) {
temp.children = [addLeaf(array.slice(1))];
}

return temp;
};

const addToTree = (tree, array) => {
if (!array || !array.length) return [];

const branchIndex = tree.findIndex(entry => entry.name === array[0]);

if (branchIndex !== -1) {
tree[branchIndex].children = [...addToTree(tree[branchIndex].children, array.slice(1))];
} else {
tree = [...tree, addLeaf(array)];
}

return tree;
};

a.forEach((entry) => {
t = addToTree(t, entry);
});

console.log(JSON.stringify(t, null, 2))

关于javascript - 如何将数据表动态转换为树状json格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53313396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com