平面数组到树 Javascript [英] Flat array to tree Javascript

查看:25
本文介绍了平面数组到树 Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在寻找一个 javascript 或 typescript 解决方案来将这个 sql 数据数组转换为树结构:

Looking for a javascript or typescript solution to turn this array of sql data into a tree structure:

我尝试过的其他一些解决方案将 id 设置为预期数组中的一个属性,但不像预期的解决方案那样将对象的键设置为.

Some other solutions I've tried set the id as a property in the expected array but not the key of the object like in the expected solution.

const sqlData = [
  { id: 1, label: 'root', parentId: 0 },
  { id: 2, label: 'ant', parentId: 1 },
  { id: 3, label: 'cat', parentId: 1 },
  { id: 4, label: 'bear', parentId: 3 },
  { id: 5, label: 'dog', parentId: 3 },
  { id: 6, label: 'elephant', parentId: 5 },
  { id: 7, label: 'frog', parentId: 1 },
];

const expected = [
  {
    1: {
      label: 'root',
      children: [
        {
          2: {
            label: 'ant',
            children: [],
          },
        },
        {
          3: {
            label: 'cat',
            children: [
              {
                4: {
                  label: 'cat',
                  children: [],
                },
              },
              {
                5: {
                  label: 'dog',
                  children: [
                    {
                      6: {
                        label: 'elephant',
                        children: [],
                      },
                    },
                  ],
                },
              },
            ],
          },
        },
        {
          7: {
            label: 'frog',
            children: [],
          },
        },
      ],
    },
  },
];

推荐答案

这可以通过利用对象引用以 O(n) 时间复杂度完成.通过在每个元素上创建一个 children 数组,然后将正确的子元素添加到其父元素的 children 数组中,您可以完成构建整个树.

This can be done with O(n) time complexity by leveraging object references. By creating a children array on each element and then adding the correct child to its parent's children array, you can accomplish building the whole tree.

const sqlData=[{id:1,label:"root",parentId:0},{id:2,label:"ant",parentId:1},{id:3,label:"cat",parentId:1},{id:4,label:"bear",parentId:3},{id:5,label:"dog",parentId:3},{id:6,label:"elephant",parentId:5},{id:7,label:"frog",parentId:1}];

const parentMap = {};
const root = [];

// Map parent positions
sqlData.forEach((el, i) => {
  parentMap[el.id] = i;
  el.children = [];
});

sqlData.forEach(({ id, parentId, label, children }) => {
  const insert = { [id]: { label, children } };
  if (parentId === 0) {
    root.push(insert);
    return;
  }
  sqlData[parentMap[parentId]].children.push(insert);
});

console.log(root);

这篇关于平面数组到树 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆