首页 > 解决方案 > 如何将树状的数组和对象的嵌套数据结构转换为具有计算/计数 id 和跟踪父 id 的项目列表?

问题描述

API 返回数组和对象的嵌套数据结构。数据以树状对象列表的形式出现,每个对象都有可能的父子关系。下面的示例代码显示了结构本身。

[{
  label: "search me",
  value: "searchme",
  children: [{

    label: "search me too",
    value: "searchmetoo",
    children: [{

      label: "No one can get me",
      value: "anonymous",
    }],
  }],
}, {
  label: "search me2",
  value: "searchme2",
  children: [{

    label: "search me too2",
    value: "searchmetoo2",
    children: [{

      label: "No one can get me2",
      value: "anonymous2",
    }],
  }],
}]

上述数据必须转换为(平面)对象数组,其中每个对象将代表前一个节点元素,但具有唯一的主键(id)。除了没有父节点的根节点之外,节点的父 ID 也等于其父节点的 ID(主键),因此父 ID 应该为空。

上面提供的源数据的目标结构然后匹配以下代码......

[{
  id: 1,                // DIAGID
  parentId: null,       // PARENTID
  label: "search me",   // DIAGNOSIS
  value: "searchme"     // DIAGTYPE
}, {
  id: 2,
  parentId: 1,
  label: "search me too",
  value: "searchmetoo"
}, {
  id: 3,
  parentId: 2,
  label: "No one can get me",
  value: "anonymous"
}, {
  id: 4,
  parentId: null,
  label: "search me2",
  value: "searchme2"
}, {
  id: 5,
  parentId: 4,
  label: "search me too2",
  value: "searchmetoo2"
}, {
  id: 6,
  parentId: 5,
  label: "No one can get me2",
  value: "anonymous2"
}]

标签: javascriptarraysrecursiondata-structuresmapping

解决方案


您可以为下一次调用采用递归方法Array#flatMap并存储parent

这种方法对所有节点递增id

const
    flatTree = (id => parent => ({ children = [], ...object }) => [
        { id: ++id, ...object, parent },
        ...children.flatMap(flatTree(id))
    ])(0),
    tree = [{ label: 'search me', value: 'searchme', children: [{ label: 'search me too', value: 'searchmetoo', children: [{ label: 'No one can get me', value: 'anonymous' }] }] }, { label: 'four', searchme: '4four' }],
    flat = tree.flatMap(flatTree(null));

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


推荐阅读