当前位置:网站首页>Flat data to tree and tree data flattening
Flat data to tree and tree data flattening
2022-06-11 02:32:00 【Xiaoxian Programming Notes】
One 、 Write it at the front
Sometimes the data structure of the data we get may not be ideal , At this point, the front-end programmer is required , Ability to transform data . For example, get flat data , But we should apply it to tree Tree component or Cascader Cascade selector assembly , Such components require that the data structure be non flat and have a hierarchical relationship tree structure .
All in all , Provide data interface to the data , May not meet the requirements , And when we have no law to change for us , The requirements and requirements come to the front-end programmers , So we have to have such data processing ability .
Here are two examples of data transformation :
First, flattening , Having a hierarchical relationship tree data , Converted to a flat structure flat data
Second, anti flattening , Flat structure flat data , Convert to... With a hierarchical relationship tree data
Two 、 Body part
2.1 Flat data is converted to tree data
Flattening function
/**
* flat : Will have a hierarchical relationship structure tree Data flattening
*
* @param treeList Having a hierarchical structure tree data
* @param flatList Variables used to receive flattened results
* @returns {*} Returns the flattened result
*/
function treeToFlat (treeList, flatList) {
// flatList.length > 9999 Is to consider the bottom line protection principle , Set for the purpose of limit protection , Can be set without or as required .
if (flatList.length > 9999) {
return
}
treeList.map(e => {
flatList.push(e)
// recursive : Call yourself conditionally , On the condition that e.children.length It's true
if (e.children && e.children.length) {
treeToFlat(e.children, flatList)
}
})
// console.log(' After flattening :', flatList)
return flatList
}
Copy code 2.2 tree Data to flat data
Anti flattening function
/**
* Anti flattening : The flat structure flat The data is transformed into... With a hierarchical relationship structure tree data
*
* @param flatList Flat structured data
* @param treeList The variable used to receive the result of de flattening
* @returns {*} Returns the de flattening result
*/
function flatToTree (flatList, treeList) {
flatList.map(e => {
// With e.pid===null, As the basis for judging whether it is the root node , Or write the dead root node directly ( If you're sure ),
// What is the basis for judging the root node , It depends on the design rules of the data , It is usually a marker to judge whether the hierarchy or the root node is represented
if (e.pid === null) {
// Avoid duplicate data
const index = treeList.findIndex(sub => sub.id === e.id)
if (index === -1) {
treeList.push(e)
}
}
flatList.map(e2 => {
if (e2.pid === e.id) {
// Avoid duplicate data
const index = e.children.findIndex(sub => sub.id === e2.id)
if (index === -1) {
e.children.push(e2)
}
}
})
})
Copy code 2.3 Complete test demo
demo The screenshot of the test results is as follows :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title> Flat data transfer tree And tree Data flattening Demo</title>
</head>
<body>
<h1> Flat data transfer tree And tree Data flattening </h1>
<script>
window.onload = function () {
test()
}
function test () {
let flatList = [],
treeList = [
{
id: 1,
pid: null,
label: ' first floor ',
value: '1',
children: [
{
id: 2,
pid: 1,
label: ' The second floor 1',
value: '2.1',
children: []
},
{
id: 3,
pid: 1,
label: ' The second floor 2',
value: '2.2',
children: []
},
{
id: 4,
pid: 1,
label: ' The second floor 3',
value: '2.3',
children: [
{
id: 5,
pid: 4,
label: ' The third level 1',
value: '3.1',
children: []
},
{
id: 6,
pid: 4,
label: ' The third level 2',
value: '3.2',
children: []
},
]
},
]
}
]
console.log(' original tree data :', JSON.parse(JSON.stringify(treeList)))
// flat
console.log('tree =>flat, After flattening :', treeToFlat(JSON.parse(JSON.stringify(treeList)), flatList))
// Anti flattening ,SON.parse(JSON.stringify()) For deep copy
console.log('flat =>tree, After anti flattening :', flatToTree(JSON.parse(JSON.stringify(flatList)), treeList))
}
/**
* flat : Will have a hierarchical relationship structure tree Data flattening
*
* @param treeList Having a hierarchical structure tree data
* @param flatList Variables used to receive flattened results
* @returns {*} Returns the flattened result
*/
function treeToFlat (treeList, flatList) {
// flatList.length > 9999 Is to consider the bottom line protection principle , Set for the purpose of limit protection , Can be set without or as required .
if (flatList.length > 9999) {
return
}
treeList.map(e => {
flatList.push(e)
// recursive : Call yourself conditionally , On the condition that e.children.length It's true
if (e.children && e.children.length) {
treeToFlat(e.children, flatList)
}
})
// console.log(' After flattening :', flatList)
return flatList
}
/**
* Anti flattening : The flat structure flat The data is transformed into... With a hierarchical relationship structure tree data
*
* @param flatList Flat structured data
* @param treeList The variable used to receive the result of de flattening
* @returns {*} Returns the de flattening result
*/
function flatToTree (flatList, treeList) {
flatList.map(e => {
// With e.pid===null, As the basis for judging whether it is the root node , Or write the dead root node directly ( If you're sure ),
// What is the basis for judging the root node , It depends on the design rules of the data , It is usually a marker to judge whether the hierarchy or the root node is represented
if (e.pid === null) {
// Avoid duplicate data
const index = treeList.findIndex(sub => sub.id === e.id)
if (index === -1) {
treeList.push(e)
}
}
flatList.map(e2 => {
if (e2.pid === e.id) {
// Avoid duplicate data
const index = e.children.findIndex(sub => sub.id === e2.id)
if (index === -1) {
e.children.push(e2)
}
}
})
})
// console.log(' After anti flattening :', treeList)
return treeList
}
</script>
</body>
</html>
Written in the back
These two flattening and anti flattening methods , I feel that there are still methods worth optimizing , But I can't think of it for the time being .
Besides , The application of recursion is also noteworthy .
Recursion I understand : Call yourself conditionally .
边栏推荐
猜你喜欢

clang-format 最全格式说明

Find - (block find)

叶酸配体的金属有机骨架材料MOFs负载5-氟尿嘧啶,西达本胺,紫杉醇,阿霉素,柔红霉素,布洛芬,喜树碱,姜黄素,藤黄酸等小分子药物

Cyclodextrin metal organic framework( β- Cd-mof) loaded with dimercaptosuccinic acid / emodin / quercetin / sucralose / diflunisal / omeprazole (OME)
![[3.delphi common components] 5 List class component](/img/c0/33b1903c73840b350fea1740eade5e.jpg)
[3.delphi common components] 5 List class component

SQL | calculate sum

SQL | 计算总和
![[parallel and distributed systems] cache learning](/img/79/de4da45aab54bb3bec240ac36e7978.png)
[parallel and distributed systems] cache learning

378. the k-th smallest element in an ordered matrix

MySQL备份与恢复
随机推荐
[untitled]
Jetpack compose box control
[parallel and distributed systems] cache learning
关于Set集合类你都知道什么?来自《卷Ⅰ》的灵魂提问
Principle of everything for fast search
Project load failed
GCC C inline assembly
Unity3d model skin changing technology
English subtitle video translated into Chinese subtitles
MySQL backup and recovery
贵金属白银和现货白银之间是什么关系
Record scroll bar position, passive, scrolltop
Kotlin let method
金属有机骨架材料Fe-MIL-53,Mg-MOF-74,Ti-KUMOF-1,Fe-MIL-100,Fe-MIL-101)负载异氟醚/甲氨蝶呤/阿霉素(DOX)/紫杉醇/布洛芬/喜树碱
1031. maximum sum of two non overlapping subarrays
JS summary of math functions in math objects
Analysis of common ADB commands
Defense measures for common vulnerabilities
Jetpack Compose Box控件
NFT insider 61:animoca brands holds US $1.5 billion of encrypted assets in 340 investments