树状数据操作

2018-08-17  本文已影响0人  炫海神鹰

目录


{
  text: '一级', // 要显示的文本
  value: 1,  // 唯一值
  checked: false, // 选中转态
  children: [{
    text: '二级-1',
    value: 11,
    checked: false,
    children: [{
      text: '三级-1',
      value: 111,
      checked: false,
    }]
  }, {
    text: '二级-2',
    value: 12,
    checked: false,
  }]
}

需要转化成以下格式

[ { text: '一级',
    value: 1,
    checked: false,
    disabled: false,
    showSign: true,
    parent: null },
  { text: '二级-1',
    value: 11,
    checked: false,
    disabled: false,
    parent: 1 },
  { text: '三级-1',
    value: 111,
    checked: false,
    disabled: false,
    parent: 11 },
  { text: '二级-2',
    value: 12,
    checked: false,
    disabled: false,
    parent: 1 } ]

代码实现

let tree = {
  text: '一级', // 要显示的文本
  value: 1,  // 唯一值
  checked: false, // 选中转态
  children: [{
    text: '二级-1',
    value: 11,
    checked: false,
    children: [{
      text: '三级-1',
      value: 111,
      checked: false,
    }]
  }, {
    text: '二级-2',
    value: 12,
    checked: false,
  }]
}
var result = []
function treeToLine(tree, treeKey, isRoot = true, root = null) {
  if (!tree || !tree.children) return result
  let obj = {}
  for (let key in tree) {
    if (tree.hasOwnProperty(key) && key !== 'children') {
      obj[key] = tree[key]
    }
  }
  obj.parent = isRoot ? null : root[treeKey]
  result.push(obj)
  for (let child of tree.children) {
    if (child && child.children) {
      treeToLine(child, treeKey, false, tree)
    } else if (child && !child.children){ // 最后一层
      child.parent = tree[treeKey]
      result.push(child)
      return result
    }
  }
}
console.log(treeToLine(tree, 'value'))

其中函数第二个参数为每层树的唯一值,用于parent进行标识所属的父节点。

实现代码:

function lineToTree(data, value = 'value', parentId = 'parent') {
  let children = 'children'

  let valueMap = [], tree = []
  data.forEach(v => {
    valueMap[v[value]] = v
  })

  data.forEach(v => {
    let parent = valueMap[v[parentId]]
    if(parent) {
      !parent[children] && (parent[children] = [])
      parent[children].push(v)
    } else {
      tree.push(v)
    }
  })
  return tree
}

其中参数value是树状结构的唯一标识,parentId是父节点的键值。

1000个节点权限树性能优化

上一篇下一篇

猜你喜欢

热点阅读