当前位置:网站首页>代码片段
代码片段
2022-06-28 14:32:00 【lanrri】
代码片段
扁平数据结构转树结构数据
/**
* 扁平数据结构转树结构数据
* @param {array} arr 扁平数据
* @param {string} pidKey 默认{pid}
* @returns {array} 树结构数据
*/
const arr2Tree = (arr, pidKey = 'pid') => {
const result = arr.reduce((res, next) => {
const nextPid = next[pidKey]
res[nextPid] ? res[nextPid].push(next) : res[nextPid] = [next]
return res
}, {})
const resultKeyArr = Object.keys(result)
resultKeyArr.map((key) => {
const resultItem = result[key]
resultItem.map((item) => {
if (result[item.id]) {
item.children = result[item.id]
}
})
})
return result[resultKeyArr[0]]
};
树结构数据结构转扁平数据
/**
* 树结构数据结构转扁平数据
* @param {array} arr 树结构数据
* @returns {array} 扁平数据
*/
const flatten = (arr) => {
return arr.reduce((flat, {children = [], ...res}) => {
return flat.concat(res, flatten(children));
}, []);
}
边栏推荐
- 力扣解法汇总522-最长特殊序列 II
- Validate palindrome string
- 哪个证券公司最大最安全 怎么办理开户最安全
- What does VPS do? What are the famous brands? What is the difference with ECS?
- Reverse a stack with recursive functions and stack operations only
- Recommended practice sharing of Zhilian recruitment based on Nebula graph
- Nature | mapping the interaction map of plant foliar flora to establish genotype phenotype relationship
- Robot range of motion (DFS)
- JS judge whether the string is empty or not
- PMP真的有用吗?
猜你喜欢
flutter 系列之:flutter 中的 offstage
Four visualization tools are recommended to solve 99% of large screen visualization projects!
Q-Tester 3.2:适用于开发、生产和售后的诊断测试软件
字节跳动埋点数据流建设与治理实践
线程的生命周期以及其中的方法
安杰思医学冲刺科创板:年营收3亿 拟募资7.7亿
Introduction to common components of IOT low code platform
Recommended practice sharing of Zhilian recruitment based on Nebula graph
Four methods of thread termination
After nearly 20 years of operation, the Mars probe software based on win 98 has been upgraded for the first time
随机推荐
猫狗队列
从小小线虫谈起——溯源神经系统进化,开启生命模拟
sort
考了这个PMP证书到底有什么好处?
@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常
dolphinscheduler2.X的安装(亲测有效)
Validate palindrome string
How to back up MySQL_ The most complete MySQL backup method in history
哪个证券公司最大最安全 怎么办理开户最安全
Maingene listed on the Hong Kong Stock Exchange: IPO with a market value of HK $4.3 billion was ignored by the market
Leetcode (167) -- sum of two numbers II - input ordered array
Tencent was underweight again by prosus, the major shareholder: the latter also cashed out $3.7 billion from JD
Kwai investment e-commerce service provider Yixin optimization
Deveco studio 3.0 editor configuration tips
基于 Nebula Graph 构建百亿关系知识图谱实践
组合总和-Leetcode
Rslo: self supervised lidar odometer (real time + high precision, icra2022)
Reverse a stack with recursive functions and stack operations only
Softing epGate PB系列网关-可将PROFIBUS总线集成到EtherNet/IP网络
Angers medical sprint scientific innovation board: annual revenue of RMB 300million and proposed fund raising of RMB 770million