大佬们 怎么给已经是tree树结构的数据赋值坐标啊

呼啦星星星
  • 72

给已知的tree树结构赋值坐标

问题:比如我已经知道了tree结构:

const treeData = [
  {
    title: 'parent 1',
    children: [
      {
        title: 'parent 1-0',
        children: [
          {
            title: 'leaf',
          },
          {
            title: 'leaf',
          },
        ],
      },
      {
        title: 'parent 1-1',
        children: [{ title:22222}],
      },
    ],
  },
  {
    title: 'parent 2',
    children: [
      {
        title: 'parent 2-0',
        children: [
          {
            title: 'leaf',
          },
          {
            title: 'leaf',
          },
        ],
      },
      {
        title: 'parent 2-1',
        children: [{ title:33333}],
      },
    ],
  },
];

我怎么给这种结构赋值坐标key啊,如下图,因为有了key才能使用tree的渲染组件例如antd的tree

const treeData = [
  {
    title: 'parent 1',
    key:'1',
    children: [
      {
        title: 'parent 1-0',
        key:'1-0',
        children: [
          {
            key:'1-0-0',
            title: 'leaf',
          },
          {
            key:'1-0-1',
            title: 'leaf',
          },
        ],
      },
      {
        title: 'parent 1-1',
        key:'1-1',
        children: [{ title:22222},key:'1-1-0'],
      },
    ],
  },
  {
    title: 'parent 2',
    key:'2',
    children: [
      {
        title: 'parent 2-0',
        key:'2-0',
        children: [
          {
            key:'2-0-0',
            title: 'leaf',
          },
          {
            key:'2-0-1',
            title: 'leaf',
          },
        ],
      },
      {
        title: 'parent 2-1',
        key:'2-1',
        children: [{ title:33333}, key:'2-1-0',],
      },
    ],
  },
];
回复
阅读 379
2 个回答

递归遍历。然后给个自增的值就好了

image.png

如果只展示且title不重复,将key指向title即可

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏