当前位置:网站首页>扁平数组和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) )
}, [])
}
边栏推荐
- [LeetCode]508. 出現次數最多的子樹元素和
- [LeetCode]515. Find the maximum value in each tree row
- Go from introduction to practice - error mechanism (note)
- 管理系统-ITclub(中)
- 北京邮电大学|用于成本和延迟敏感的虚拟网络功能放置和路由的多智能体深度强化学习
- Special training of guessing game
- Simulink导出FMU模型文件方法
- Codeforces Round #717 (Div. 2)
- PCIe knowledge point -008: structure of PCIe switch
- Example of using gbase 8A OLAP function group by grouping sets
猜你喜欢

Simulink导出FMU模型文件方法
![[LeetCode]动态规划解分割数组II[Arctic Fox]](/img/a1/4644206db3e14c81f9f64e4da046bf.png)
[LeetCode]动态规划解分割数组II[Arctic Fox]

.NET学习笔记(五)----Lambda、Linq、匿名类(var)、扩展方法

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

Open source technology exchange - Introduction to Chengying, a one-stop fully automated operation and maintenance manager

我想我要开始写我自己的博客了。

Simulink method for exporting FMU model files

清华大学教授:软件测试已经走入一个误区——“非代码不可”

C语言程序设计详细版 (学习笔记1) 看完不懂,我也没办法。

使用Jmeter进行性能测试的这套步骤,涨薪2次,升职一次
随机推荐
Yarn中RMApp、RMAppAttempt、RMContainer和RMNode状态机及其状态转移
regular expression
軟件測試自動化測試之——接口測試從入門到精通,每天學習一點點
A method of go accessing gbase 8A database
软件测试自动化测试之——接口测试从入门到精通,每天学习一点点
∫(0→1) ln(1+x) / (x ² + 1) dx
Codeforces Round #723 (Div. 2)
Golang uses regularity to match substring functions
Quick excel export
Little known MySQL import data
[LeetCode]161. Edit distance of 1
GBase 8a的create database 会被查询耗时很长怀疑卡住的现象分析
C语言程序设计详细版 (学习笔记1) 看完不懂,我也没办法。
二维数组中修改代价最小问题【转换题意+最短路径】(Dijkstra+01BFS)
How to do function test well? Are you sure you don't want to know?
大厂常用软件测试面试题三(附答案)
Simulink method for exporting FMU model files
List of language weaknesses --cwe, a website worth learning
真香,自从用了Charles,Fiddler已经被我彻底卸载了
Sharing | intelligent environmental protection - ecological civilization informatization solution (PDF attached)