javascript中树结构数据转换
2021/12/23 14:07:20
本文主要是介绍javascript中树结构数据转换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/** 扁平化数据变成树 */ const _iteration = (_target = [], { _id = "id", pid = "pid", children = "children", rootId = "root" } = {}) => { let _parentMap = new Map() const target = JSON.parse(JSON.stringify(_target)) let result = []; for (const item of target) { if (_parentMap.has(item[_id])) { item[children] = _parentMap.get(item[_id])[children] } else { item[children] = [] } _parentMap.set(item[_id], item) if (_parentMap.has(item[pid])) { _parentMap.get(item[pid])[children].push(item) } else { _parentMap.set(item[pid], { [children]: [item] }) } if (String(item[pid]) === String(rootId)) { result.push(item) } } return { result, _parentMap }; } /** 扁平化数据变成树 */ const listToTree = (_target = [], { id = "id", parentId = "parentId" } = {}) => { let info = _target.reduce((map, node) => (map[node[id]] = node, node.children = [], map), {}) return _target.filter(node => { info[node[parentId]] && info[node[parentId]].children.push(node) return !node[parentId] }) } // /** 扁平化数据变成树 */ const dataToTree = (_target = [], { id = "id", parentId = "parentId" } = {}) => { return res = _target.filter(r => !r[parentId]).map(r => ({ ...r, children: _target.filter(rr => rr[parentId] === r[id]) })) }
这篇关于javascript中树结构数据转换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26Mybatis官方生成器资料详解与应用教程
- 2024-11-26Mybatis一级缓存资料详解与实战教程
- 2024-11-26Mybatis一级缓存资料详解:新手快速入门
- 2024-11-26SpringBoot3+JDK17搭建后端资料详尽教程
- 2024-11-26Springboot单体架构搭建资料:新手入门教程
- 2024-11-26Springboot单体架构搭建资料详解与实战教程
- 2024-11-26Springboot框架资料:新手入门教程
- 2024-11-26Springboot企业级开发资料入门教程
- 2024-11-26SpringBoot企业级开发资料详解与实战教程
- 2024-11-26Springboot微服务资料:新手入门全攻略