当前位置:网站首页>Conversion between flat array and JSON tree
Conversion between flat array and JSON tree
2022-06-27 22:17:00 【You must try, but don't worry】
Flat arrays -> JSON Trees
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 The value returned by the last call callback , Or initial value
prev[item.id] = item
return prev
}, {
})
let result = []
for(let item of flatArr) {
if(!item.parent_id) {
// Class A
result.push(item)
continue
}
// Can get here Definitely not the first level
// Find parent first
if(item.parent_id in map) {
let parent = map[item.parent_id] // Parent
// Classic and concise value taking , No value initialization
;(parent.children || (parent.children = [])).push(item)
}
}
return result
}
JSON Trees -> Flat arrays
const JSONThreeToFlat = tree => {
return tree.reduce((prev, item) => {
const {
children = [], ...rest } = item
return prev.concat( [{
...rest}], JSONThreeToFlat(children) )
}, [])
}
边栏推荐
- Deep learning has a new pit! The University of Sydney proposed a new cross modal task, using text to guide image matting
- Yarn中RMApp、RMAppAttempt、RMContainer和RMNode状态机及其状态转移
- 读写分离-Mysql的主从复制
- Figure countdownlatch and cyclicbarrier based on AQS queue
- A method of go accessing gbase 8A database
- Contest 2050 and Codeforces Round #718 (Div. 1 + Div. 2)
- 扁平数组和JSON树的转换
- 不外泄的测试用例设计秘籍--模块测试
- 二维数组中修改代价最小问题【转换题意+最短路径】(Dijkstra+01BFS)
- Software test automation test -- interface test from entry to proficiency, learn a little every day
猜你喜欢

01 golang environment construction

Go from introduction to practice - error mechanism (note)

6G显卡显存不足出现CUDA Error:out of memory解决办法

美团20k软件测试工程师的经验分享

YOLOv6:又快又准的目标检测框架开源啦

BAT测试专家对web测试和APP测试的总结

管理系统-ITclub(中)

GBase 8a的create database 会被查询耗时很长怀疑卡住的现象分析

The create database of gbase 8A takes a long time to query and is suspected to be stuck

真香,自从用了Charles,Fiddler已经被我彻底卸载了
随机推荐
Gbase 8A OLAP analysis function cume_ Example of dist
Codeforces Round #719 (Div. 3)
[LeetCode]515. 在每个树行中找最大值
Figure countdownlatch and cyclicbarrier based on AQS queue
01 golang environment construction
Dynamic refresh mapper
【mysql实战】查询语句实战演示
MONTHS_ Between function use
深度学习又有新坑了!悉尼大学提出全新跨模态任务,用文本指导图像进行抠图
[LeetCode]572. 另一棵树的子树
軟件測試自動化測試之——接口測試從入門到精通,每天學習一點點
Codeforces Round #716 (Div. 2)
Test birds with an annual salary of 50w+ are using this: JMeter script development -- extension function
[LeetCode]513. 找树左下角的值
C语言程序设计详细版 (学习笔记1) 看完不懂,我也没办法。
Little known MySQL import data
BAT测试专家对web测试和APP测试的总结
二维数组中修改代价最小问题【转换题意+最短路径】(Dijkstra+01BFS)
Acwing week 57 longest continuous subsequence - (binary or tree array)
[leetcode] dynamic programming solution partition array ii[arctic fox]