js 一维数组,转成嵌套数组

// 情况一:
// 数据源
var
egs = [ {name_1: 'name_1...'}, {name_2: 'name_4...'}, {name_3: 'name_3...'}, {name_0: 'name_0...'}, ].reverse()
// 最终想要的数据形式
// {name_1: 'name_1...', // children: [ // {name_2: 'name_2...', // children: [ // {name_3: 'name_3...'}, // ] // } // ] // } var result = {} var key ='children' s(egs) function s(arrs) { arrs.forEach((o, i) => { console.log('---'+ i + ': ', result) if (!result[key]) { result[key] = [o] } else { o[key] = [result] result = o } }) } console.log(result)
// 情况二:
// pId 对应父级 id
let arr = [
    { pId: '-1', id: '0', name: '父级1' },
    { pId: '0', id: '1', name: '父级1-1' },
    { pId: '0', id: '2', name: '父级1-2' },
    { pId: '2', id: '21', name: '子级21' },
  ]

  function buildTree (arr) {
    let temp = {}
    let tree = {}
    // 数组转 键值对
    arr.forEach(item => {
      temp[item.id] = item
    })

    let tempKeys = Object.keys(temp)
    tempKeys.forEach(key => {
      // 获取当前项
      let item = temp[key]
      // 当前项 pId
      let _itemPId = item.pId
      // 获取父级项
      let parentItemByPid = temp[_itemPId]
      if (parentItemByPid) {
        if (!parentItemByPid.children) {
          parentItemByPid.children = []
        }
        parentItemByPid.children.push(item)
      } else {
        tree[item.id] = item
      }
    })
    // 对象转数组并返回
    return Object.keys(tree).map(key => tree[key])
  }
 
 

 

posted @ 2018-01-24 10:10  gauseen  阅读(6897)  评论(0编辑  收藏  举报