树结构,子节点是对象的方式,希望将对象转化成数组?(JS)

Smile丶
  • 15

有这样一个树结构:希望通过一个函数,将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,
          },
        ],
      },
    ],
  },
];
回复
阅读 258
1 个回答
const convert = data => data ? Object.entries(data).map(([ key, val ]) => ({
    id: key,
    ...val,
    children: convert(val.children)
})) : undefined
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏