Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js保存树状数据 #7

Open
ZSI2017 opened this issue Mar 28, 2018 · 0 comments
Open

js保存树状数据 #7

ZSI2017 opened this issue Mar 28, 2018 · 0 comments

Comments

@ZSI2017
Copy link
Owner

ZSI2017 commented Mar 28, 2018

通常,在管理后台的数据交互中,都会使用到tree 来保存大量的带有父子关系的数据。这种tree ,可能是对象数组的形式存放着

    [{
      content:"1",
      parent1:"parent1",
      id:"1",
      children:[{
              content:"222",
              id:"11",
              child1:"child1"
            },{
              content:"333",
              id:"22",
              child2:"child2"
            },{
              content:"444",
              id:"33",
              child3:"child3"
           }]
    }]

类似上面这样的数据存储格式,非常方便的存储,但是在查找的时候,就需要利用递归或者循环不断的遍历子节点。所以就可以修改成下面这样,加一个pid 字段

    [{
      id:"1",
      content:"1",
      parent1:"parent1"
    },{
      pid:"1",
      id:"11",
      content:"222",
      child1:"child1"
    },{
      pid:"1",
      id:"22",
      content:"333",
      child2:"child2"
    },{
      pid:"1",
      id:"33",
      content:"444",
      child3:"child3"
    }]

从tree到数组的转换,可以把查找一次循环的范围内,同时在后端存储时,也节省了表空间。
然后,就涉及到了树与数组之间的相互转换

  • tree -> array

      const getTreeToArray = (menu) => {
        let result = []
        let data = JSON.parse(JSON.stringify(menu))
        data.forEach(function(item,idx){
          result.push(item)
        })
        result.forEach(function(item,idx){
          if(item.children) {
            result = result.concat(item.children);
            delete item.children
          }
        })
        return result;
      }
    
  • array -> tree

    const getArrayToTree = (menu) => {
      let result = [],cloneObj= {};
      let data = Array.prototype.slice.call(menu);
      data.forEach(function(item,idx){
        cloneObj[item["id"]] = data[idx]
      })
      data.forEach(function(item,idx){
        var haveChild = cloneObj[item['pid']];
        if(haveChild) {
          !haveChild['children'] && (haveChild['children'] = [])
          haveChild['children'].push(item)
        }else {
          result.push(item)
        }
      })
      return result;
    }
    
    
@ZSI2017 ZSI2017 changed the title js传递树状结构数据 js保存树状数据 Mar 28, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant