JS遍历树形数据
2023-09-27 14:22:17 时间
树形数据结构遍历某个key值
深度优先遍历(DFS)
let tree = [{
id: '1',
name: '节点1',
children: [{
id: '1-1',
name: '节点1-1'
}]
}, {
id: '2',
name: '节点2',
children: [{
id: '2-1',
name: '节点2-1'
}, {
id: '2-2',
name: '节点2-2',
children: [{
id: '2-2-1',
name: '节点2-2-1'
}]
}]
}, {
id: '3',
name: '节点3'
}, {
id: '4',
name: '节点4'
}]
function treeIterator(tree, func) {
tree.forEach((node) => {
func(node)
node.children && treeIterator(node.children, func)
})
}
treeIterator(tree, (node) => {
console.log(node.name)
})
循环实现
function treeIterator(tree, func) {
let node, curTree = [...tree]
while ((node = curTree.shift())) {
func(node)
node.children && curTree.unshift(...node.children)
}
}
treeIterator(tree, (node) => {
console.log(node.name)
})
广度优遍历
function treeIterator(tree, func) {
let node, curTree = [...tree]
while ((node = curTree.shift())) {
func(node)
node.children && curTree.push(...node.children)
}
}
treeIterator(tree, (node) => {
console.log(node.name)
})
相关文章
- js遍历Object所有属性
- JS中数组与对象的遍历方法实例小结
- eclipse build workspace太慢或者 js出错问题解决
- 这事要从node node.js说起
- 『XXG JS』JavaScript 数组 - 遍历
- JS正则表达式
- js遍历树形结构并返回所有的子节点id值
- vue.js:v-model结合radio的使用
- vue.js v-for遍历对象
- vue.js v-bind的基本使用语法
- 「经典题」原生js的11种循环遍历,你掌握了几种?
- 使用Egg.js编写RestfulAPI接口(二)配置跨域
- js 控制浏览条位置
- js 字典
- js的15种循环遍历,你掌握了几种【转】
- 正则表达式专题(JS版)之9、下载PDF版
- js遍历json
- C#后台执行JS
- JS中的倒计时
- js:可能是最全的js遍历方法
- js - 在拼接字符串中动态submit当前form
- Vue.js双向绑定的实现原理和模板引擎实现原理(##########################################)
- 【Node.JS】buffer类缓冲区
- AngularJS 前端JS框架
- vue.js之数据传递和数据分发slot