需求
有一段数据如下,期望获取 children 下及 children 所有节点个数,并且能根据条件获取符合条件的节点个数。
let data = [
{
id: 1,
type: 0,
name: '1',
children: [
{ id: 2, type: 1, name: '2' },
{
id: 3,
type: 0,
name: '3',
children: [
{ id: 4, type: 1, name: '4' },
{ id: 5, type: 1, name: '5' },
{ id: 6, type: 0, name: '6' },
],
},
{ id: 7, type: 1, name: '7' },
{ id: 8, type: 1, name: '8' },
{ id: 9, type: 0, name: '9' },
],
},
];
经过处理转换后
let data2 = [
{
id: 1,
type: 0,
name: '1',
total: 8, // 获取下面的 children 及 chilren 下面的数据总数
total_0: 3, // 获取下面的 children 及 chilren 下面的 type 为 0 数据总数
total_1: 5, // 获取下面的 children 及 chilren 下面的 type 为 1 数据总数
children: [
{ id: 2, type: 1, name: '2' },
{
id: 3,
type: 0,
name: '3',
total: 3, // 获取下面的 children 及 chilren 下面的数据总数
total_0: 1, // 获取下面的 children 及 chilren 下面的 type 为 0 数据总数
total_1: 2, // 获取下面的 children 及 chilren 下面的 type 为 1 数据总数
children: [
{ id: 4, type: 1, name: '4' },
{ id: 5, type: 1, name: '5' },
{ id: 6, type: 0, name: '6' },
],
},
{ id: 7, type: 1, name: '7' },
{ id: 8, type: 1, name: '8' },
{ id: 9, type: 0, name: '9' },
],
},
];
题解
function deepTree(array, node = {}) {
let newArray = array;
debugger
for (let index = 0; index < newArray.length; index++) {
const element = newArray[index];
node.total = (node.total || 0) + 1;
if (
Object.prototype.toString.call(element) === '[object Object]' &&
Object.prototype.hasOwnProperty.call(element, 'children')
) {
const children = element.children;
const deepChildren = deepTree(children, element);
node.total = (node.total || 0) + (element.total || 0);
}
}
return newArray;
}
const newData = deepTree(data);
console.log('newData', newData);
参考文章
- https://juejin.cn/post/6882627409393221646
- https://blog.csdn.net/qq_41883423/article/details/112377108#:~:text=深度优先遍历是指,都被访问完为止。
- https://blog.csdn.net/lb812913059/article/details/83313360#:~:text=深度优先遍历:,序遍历、后序遍历。
- https://medium.com/@iampika/javascript-trees-b8f3b4261c3a
- https://stackoverflow.com/questions/60891070/how-to-calculate-the-sum-of-the-children-in-a-general-tree-using-javascript
- https://stackoverflow.com/questions/39375531/javascript-tree-structure-traverse-tree-structure-and-show-the-sum-the-count-a
- https://dev.to/ggenya132/depth-first-traversal-in-javascript-3ehp
- https://medium.com/swlh/traversing-trees-breadth-first-and-depth-first-searches-with-javascript-316f23c9fe8f
- https://blog.bitsrc.io/depth-first-search-of-a-binary-tree-in-javascript-874701d8210a
上一篇
TensorFlow 使用笔记:shape, rank, dimension 理解及 tf.image.nonMaxSuppression() 函数
记录 TensorFlow 学习笔记,包括 TensorFlow 的 shape, rank, dimension 理解以及 TensorFlow.js tf.image.nonMaxSuppression() 函数的使用。文章内容涵盖了对象检测模型的训练以及 TensorFlow.js 的相关知识。
下一篇
使用 JavaScript 获取 PDF 页码
本文介绍如何使用 JavaScript 获取 PDF 文件的页码数量。文中提供了一个使用 `pdfjs-dist` 库的代码示例,并讲解了如何加载 PDF 文件并获取其页数。