js将有父子关系的数据转换成树形结构(tree)数据

Vue.prototype.translateDataToTree = (data) => {
  let parents = data.filter(value => value.pid == 'undefined' || value.pid == null)
  let children = data.filter(value => value.pid !== 'undefined' && value.pid != null)
  let translator = (parents, children) => {
    parents.forEach((parent) => {
      children.forEach((current, index) => {
        if (current.pid === parent.id) {
          let temp = JSON.parse(JSON.stringify(children))
          temp.splice(index, 1)
          translator([current], temp)
          typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]
        }
      }
      )
    }
    )
  }

  translator(parents, children)

  return parents
}

你可能感兴趣的:(js,javascript,vue.js,前端)