gpt4 book ai didi

javascript - 使用 Javascript ECMAScript 6 将表数据转换为分层树数据的算法

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

我有一个 JSON 表数据,想要转换为 JSON 树数据,如下所示。我正在使用任何新的 ECMAScript 6 运算符或具有函数式方法的语句(不是通过 ES5 的标准递归算法)在 JavaScript 中寻找一种有效的算法?

表格数据:

[
{
"Children":"4th Grand Father"
},
{
"Name":"4th Grand Father",
"Children":"3rd Grand Father"
},
{
"Name":"3rd Grand Father",
"Children":"2nd Grand Father"
},
{
"Name":"2nd Grand Father",
"Children":"Grand Father"
},
{
"Name":"Grand Father",
"Children":"Father"
},
{
"Name":"Grand Father",
"Children":"Uncle"
},
{
"Name":"Uncle",
"Children":"Cousin"
},
{
"Name":"Father",
"Children":"Brother"
},
{
"Name":"Father",
"Children":"Me"
}
]

树数据:

[
{
"Name": "4th Grand Father",
"Children": [
{
"Name": "3rd Grand Father",
"Children": [
{
"Name": "2nd Grand Father",
"Children": [
{
"Name": "Grand Father",
"Children": [
{
"Name": "Father",
"children": [
{
"Name": "Brother"
},
{
"Name": "Me"
}
]
},
{
"Name": "Uncle",
"children": [
{
"Name": "Cousin"
}
]
}
]
}
]
}
]
}
]
}
]

最佳答案

您可以使用这个 ES6 函数,它使用 Map、箭头函数、解构参数赋值。您甚至可以用扩展语法替换 concat 调用,但我认为这不会带来任何好处:

const makeTree = (data) => {
const hash = data.reduce ( (acc, {Name, Children}) =>
acc.set(Name, (acc.get(Name) || []).concat(Children))
, new Map );

const recurse = (Name) => hash.has(Name)
? { Name, Children: hash.get(Name).map(recurse) }
: { Name };
return recurse(undefined).Children;
}

// Sample data
const data = [
{
"Children":"4th Grand Father"
},
{
"Name":"4th Grand Father",
"Children":"3rd Grand Father"
},
{
"Name":"3rd Grand Father",
"Children":"2nd Grand Father"
},
{
"Name":"2nd Grand Father",
"Children":"Grand Father"
},
{
"Name":"Grand Father",
"Children":"Father"
},
{
"Name":"Grand Father",
"Children":"Uncle"
},
{
"Name":"Uncle",
"Children":"Cousin"
},
{
"Name":"Father",
"Children":"Brother"
},
{
"Name":"Father",
"Children":"Me"
}
];

const result = makeTree(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

说明:

hash 变量是从一个空的 Map 构建的,将记录添加到由 Name 键控的变量中。链接到每个键的值是子信息,作为数组。当遇到相同的 Name 时(即 acc.get(Name) 返回一些东西), child 被添加到已经存在的数组中,否则 (|| [ ]) 创建一个空数组并将子项添加到该数组中。

一旦 hash 完成,层次结构的顶部由其缺失的 Name(undefined)获取,并通过递归子级在哈希中查找并添加到最终对象。

由于结果对象是一个具有Children 数组的对象,而所需的结果实际上就是该数组,因此返回的是Children 属性。 p>

关于javascript - 使用 Javascript ECMAScript 6 将表数据转换为分层树数据的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43033763/

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