tree

作者: xueyueshuai | 来源:发表于2023-09-04 10:00 被阅读0次

export const listToTree = (list, startPid = 0, varId = "id", varPid = "pid", varChildren = "children") => {
  list = JSON.parse(JSON.stringify(list))

  let getChildren = (pid) => {
    let findChildren = list.filter(item => item[varPid] == pid)
    if (findChildren.length) {
      findChildren = findChildren.map(item => {
        item[varChildren] = getChildren(item[varId])
        return item
      })
    }
    return findChildren
  }

  return getChildren(startPid)
}
export const treeToList = (tree, startPid = 0, varId = "id", varPid = "pid", varChildren = "children") => {
  let children = JSON.parse(JSON.stringify(tree))

  let returnList = [];

  let eachToList = (children, pid) => {
    children.forEach(item => {
      let eachItem = {}
      Object.keys(item).map(keyName => {
        if (keyName !== varChildren) {
          eachItem[keyName] = item[keyName]
        }
      })
      eachItem[varPid] = pid;
      returnList.push(eachItem)

      if (item[varChildren] && item[varChildren].length) {
        eachToList(item[varChildren], item[varId])
      }
    })

  };

  eachToList(children, startPid)

  return returnList
}

相关文章

网友评论

      本文标题:tree

      本文链接:https://www.haomeiwen.com/subject/gmvepdtx.html