当前位置:网站首页>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 .

原网站

版权声明
本文为[Xiaoxian Programming Notes]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110140193074.html