How to realize the reorganization of arrays gracefully

classify and reorganize according to the value of a field

Source data:

var _arr = [{
    aId: 1,
    bId: 11,
    cId: 112,
}, {
    aId: 1,
    bId: 11,
    cId: 113,
}, {
    aId: 1,
    bId: 12,
    cId: 114,
}, {
    aId: 2,
    bId: 21,
    cId: 211,
}]

expectation:

[{
    aId: 1,
    children: [{
        bId: 11,
        children: [{
            cId: 112
        }, {
            cId: 113
        }]
    }, {
        bId: 12,
        children: [{
            cId: 114
        }]
    }]
}, {
    aId: 2,
    children: [{
        bId: 21,
        children: [{
            cId: 211
        }]
    }]
}]
Jun.03,2021

function trans (arr, keys) {
  let result = []
  let keyToRef = {}
  let len = keys.length
  arr.forEach(cur => {
    let obj
    let cacheKey = ''
    for (let i = 0; i < len; iPP) {
      let key = keys[i]
      cacheKey += key + cur[key]
      let ref = keyToRef[cacheKey]
      if (ref) {
        obj = ref
      } else {
        ref = i === 0 ? result : obj.children ? obj.children : obj.children = []
        obj = {
          [key]: cur[key]
        }
        keyToRef[cacheKey] = obj
        ref.push(obj)
      }
    }
  })
  return result
}
trans(_arr, ['aId', 'bId', 'cId'])

function rebuild (arr, key) {
  let res = []
  let keycopy = JSON.parse(JSON.stringify(key))
  let k = keycopy.shift()
  while (arr.length) {
    let obj = {}
    obj[k] = arr[0][k]
    let arrcopy = JSON.parse(JSON.stringify(arr))
    obj.children = arrcopy.filter(val => val[k] === obj[k]).map(val => {
      delete val[k]
      return val
    })
    res.push(obj)
    arr = arr.filter(val => val[k] !== obj[k])
  }
  return res.map(val => keycopy.length ? {
    ...val,
    children: rebuild(val.children, keycopy)
  } : val)
}
rebuild(_arr,['aId','bId'])
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b37229-2b8c0.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b37229-2b8c0.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?