javascript - 如何将树状的数组和对象的嵌套数据结构转换为具有计算/计数 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"
}]
解决方案
您可以为下一次调用采用递归方法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; }
推荐阅读
- machine-learning - PyTorch 种子会影响 dropout 层吗?
- vue.js - 理解 VueJS 中的组件嵌套
- javascript - JavaScript:如何按顺序加载图像
- reporting-services - 如何修复 SSRS 中的饼图大小
- php - Wordpress 评论顺序错误且 gravatar 无法正常工作
- sql-server - 使用具有 NameSpaces 的 SQL Server 遍历 XML 节点
- matlab - 如何从矩阵中删除具有相同数字的组合行并仅保留其中一种组合?
- python - Anaconda 安装失败。安装 vscode 失败
- javascript - JavaScript:为空/空对象数组赋值
- xml - 在 Golang 中的 XML 字符串中添加外部标签