当前位置:网站首页>扁平数组和JSON树的转换
扁平数组和JSON树的转换
2022-06-27 19:45:00 【你一定要努力,但千万别着急】
扁平数组 -> JSON树
let flatArr = [
{
id: 1, title: "title1", parent_id: 0 },
{
id: 2, title: "title2", parent_id: 0 },
{
id: 3, title: "title2-1", parent_id: 2 },
{
id: 4, title: "title3-1", parent_id: 3 },
{
id: 5, title: "title4-1", parent_id: 4 },
{
id: 6, title: "title3-2", parent_id: 3 }
]
const flatArrToJSONTree = arr => {
let map = flatArr.reduce((prev, item) => {
// prev 上一次调用回调返回的值,或初始值
prev[item.id] = item
return prev
}, {
})
let result = []
for(let item of flatArr) {
if(!item.parent_id) {
// 一级
result.push(item)
continue
}
// 能到这里 肯定不是第一级
// 先找到父级
if(item.parent_id in map) {
let parent = map[item.parent_id] // 父级
// 经典简洁的有值取值,无值初始化
;(parent.children || (parent.children = [])).push(item)
}
}
return result
}
JSON树 -> 扁平数组
const JSONThreeToFlat = tree => {
return tree.reduce((prev, item) => {
const {
children = [], ...rest } = item
return prev.concat( [{
...rest}], JSONThreeToFlat(children) )
}, [])
}
边栏推荐
- Array assignment
- [MySQL] database function clearance Tutorial Part 2 (window function topic)
- \w和[A-Za-z0-9_],\d和[0-9]等价吗?
- Summary of gbase 8A database user password security related parameters
- Management system itclub (Part 2)
- Contest 2050 and Codeforces Round #718 (Div. 1 + Div. 2)
- [LeetCode]508. 出現次數最多的子樹元素和
- Open source technology exchange - Introduction to Chengying, a one-stop fully automated operation and maintenance manager
- 二维数组中修改代价最小问题【转换题意+最短路径】(Dijkstra+01BFS)
- "Apprendre cette image" apparaît sur le Bureau win11 comment supprimer
猜你喜欢

Test birds with an annual salary of 50w+ are using this: JMeter script development -- extension function

Stm32f107+lan8720a use stm32subemx to configure network connection +tcp master-slave +udp app

Stm32cubeide1.9.0\stm32cubemx 6.5 f429igt6 plus lan8720a, configure eth+lwip

win11桌面出現“了解此圖片”如何删除

"Apprendre cette image" apparaît sur le Bureau win11 comment supprimer
![\W and [a-za-z0-9_], \Are D and [0-9] equivalent?](/img/96/2649c9cf95b06887b57fd8af2d41c2.png)
\W and [a-za-z0-9_], \Are D and [0-9] equivalent?

Knowledge sorting of exception handling

不外泄的测试用例设计秘籍--模块测试

使用Fiddler模拟弱网测试(2G/3G)

读写分离-Mysql的主从复制
随机推荐
如何做好功能测试?你确定不想知道吗?
记一次List对象遍历及float类型判断大小
\w和[A-Za-z0-9_],\d和[0-9]等价吗?
MYSQL和MongoDB的分析
How to design an elegant caching function
[LeetCode]186. Flip word II in string
Remote invocation of microservices
北京邮电大学|用于成本和延迟敏感的虚拟网络功能放置和路由的多智能体深度强化学习
使用Fiddler模拟弱网测试(2G/3G)
How to delete "know this picture" on win11 desktop
Codeforces Round #717 (Div. 2)
It smells good. Since I used Charles, Fiddler has been completely uninstalled by me
[LeetCode]508. 出現次數最多的子樹元素和
Go from introduction to actual combat - task cancellation (note)
Experience sharing of meituan 20K Software Test Engineers
YOLOv6:又快又准的目标检测框架开源啦
Quick excel export
[LeetCode]515. 在每个树行中找最大值
我想我要开始写我自己的博客了。
QT large file generation MD5 check code