当前位置:网站首页>扁平数组和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) )
}, [])
}
边栏推荐
- GBase 8a OLAP分析函数cume_dist的使用样例
- Stm32f107+lan8720a use stm32subemx to configure network connection +tcp master-slave +udp app
- 管理系统-ITclub(中)
- 【MySQL】数据库函数通关教程下篇(窗口函数专题)
- Go from introduction to practice - error mechanism (note)
- Simulink method for exporting FMU model files
- win11桌面出現“了解此圖片”如何删除
- [LeetCode]30. Concatenate substrings of all words
- Common methods of string class
- 北京邮电大学|用于成本和延迟敏感的虚拟网络功能放置和路由的多智能体深度强化学习
猜你喜欢
随机推荐
Codeforces Round #716 (Div. 2)
Example of using gbase 8A OLAP function group by grouping sets
[LeetCode]161. 相隔为 1 的编辑距离
[LeetCode]30. Concatenate substrings of all words
Array assignment
Acwing week 57 longest continuous subsequence - (binary or tree array)
\W and [a-za-z0-9_], \Are D and [0-9] equivalent?
Stm32cubeide1.9.0\stm32cubemx 6.5 f429igt6 plus lan8720a, configure eth+lwip
Gao fushuai in the unit testing industry, pytest framework, hands-on teaching, will do this in the future test reports~
Summary of gbase 8A database user password security related parameters
Go from introduction to actual combat - only any task is required to complete (notes)
二维数组中修改代价最小问题【转换题意+最短路径】(Dijkstra+01BFS)
Go 访问GBase 8a 数据库的一个方法
Stm32f107+lan8720a use stm32subemx to configure network connection +tcp master-slave +udp app
GBase 8a OLAP分析函数cume_dist的使用样例
[LeetCode]513. 找树左下角的值
Use Fiddler to simulate weak network test (2g/3g)
Système de gestion - itclub (II)
真香,自从用了Charles,Fiddler已经被我彻底卸载了
CDH集群之YARN性能调优

![\w和[A-Za-z0-9_],\d和[0-9]等价吗?](/img/96/2649c9cf95b06887b57fd8af2d41c2.png)







