树结构,子节点是对象的方式,希望将对象转化成数组?(JS)
有这样一个树结构:希望通过一个函数,将key变一个field: key, children从对象变成数组的形式。
const revert = () => {
... 这个函数不知道怎么写
}
const revertResult = revert(tree)
const tree = {
a: {
name: "甲",
children: {
childA: {
name: "乙",
random: 1,
},
childB: {
name: "丙",
random: 2,
},
childC: {
name: "丁",
children: {
childC1: {
name: "末",
random: 4,
},
childC2: {
name: "担",
random: 5,
},
},
},
},
},
b: {
id: "张全蛋",
name: "丑",
children: {
childA: {
name: "张三",
random: 5,
},
childB: {
name: "李四",
random: 5,
},
childC: {
name: "王五",
children: {
childC1: {
name: "李二蛋",
random: 5,
},
childC2: {
name: "张全蛋",
random: 5,
},
},
},
},
},
};
期望结果
const convertResult = [
{
id: "a",
name: "甲",
children: [
{
id: "childA",
name: "乙",
random: 1,
},
{
id: "childB",
name: "丙",
random: 2,
},
{
id: "childC",
name: "丁",
children: [
{
id: "childC1",
name: "末",
random: 4,
},
{
id: "childC2",
name: "担",
random: 5,
},
],
},
],
},
{
id: "b",
name: "丑",
children: [
{
id: "childA",
name: "张三",
random: 5,
},
{
id: "childB",
name: "李四",
random: 5,
},
{
id: "childC",
name: "王五",
children: [
{
id: "childC1",
name: "李二蛋",
random: 4,
},
{
id: "childC2",
name: "张全蛋",
random: 5,
},
],
},
],
},
];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)