当前位置:网站首页>代码片段
代码片段
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));
}, []);
}
边栏推荐
- 2022下半年软考考试时间安排已确定!
- What does VPS do? What are the famous brands? What is the difference with ECS?
- 【mysql学习笔记24】索引设计原则
- @Controlleradvice + @exceptionhandler handles controller layer exceptions globally
- 【二叉树】从叶结点开始的最小字符串
- 猫狗队列
- 线程的生命周期以及其中的方法
- Thread life cycle and its methods
- Clipping of raster vector data
- 开闭原则
猜你喜欢

Softing epGate PB系列网关-可将PROFIBUS总线集成到EtherNet/IP网络

Flutter series: offstage in flutter

sort

荐书丨《大脑通信员》:如果爱情只是化学反应,那还能相信爱情吗?

物联网低代码平台常用《组件介绍》

2022下半年软考考试时间安排已确定!

Rslo: self supervised lidar odometer (real time + high precision, icra2022)

腾讯再遭大股东Prosus减持:后者还从京东套现37亿美元

PMP真的有用吗?

Opengauss kernel: analysis of SQL parsing process
随机推荐
Gas station (greedy)
Why can't Bert completely kill the BM25??
open3d里pointcloud和numpy数组之间的转化
PMP真的有用吗?
Leetcode(406)——根据身高重建队列
Leetcode (665) -- non decreasing column
3. Overall UI architecture of the project
Research and Simulation of chaotic digital image encryption technology based on MATLAB
A queue of two stacks
Only four breakthrough Lenovo smart Summer Palace in mainland China won the "IDC Asia Pacific Smart City Award in 2022"
Maingene listed on the Hong Kong Stock Exchange: IPO with a market value of HK $4.3 billion was ignored by the market
有效提高绩效面谈的10个关键点
腾讯再遭大股东Prosus减持:后者还从京东套现37亿美元
Leetcode (167) -- sum of two numbers II - input ordered array
Talking from the little nematode -- tracing the evolution of nervous system and starting life simulation
Thread life cycle and its methods
安杰思医学冲刺科创板:年营收3亿 拟募资7.7亿
一个bug肝一周...忍不住提了issue
单一职责原则
Rslo: self supervised lidar odometer (real time + high precision, icra2022)