toArrayTree.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var setupDefaults = require('./setupDefaults')
  2. var map = require('./map')
  3. var orderBy = require('./orderBy')
  4. var clone = require('./clone')
  5. var includes = require('./includes')
  6. var each = require('./each')
  7. var remove = require('./remove')
  8. var assign = require('./assign')
  9. function strictTree (array, optChildren) {
  10. each(array, function (item) {
  11. if (item.children && !item.children.length) {
  12. remove(item, optChildren)
  13. }
  14. })
  15. }
  16. /**
  17. * 将一个带层级的数据列表转成树结构
  18. *
  19. * @param {Array} array 数组
  20. * @param {Object} options {strict: false, parentKey: 'parentId', key: 'id', children: 'children', data: 'data'}
  21. * @return {Array}
  22. */
  23. function toArrayTree (array, options) {
  24. var opts = assign({}, setupDefaults.treeOptions, options)
  25. var optStrict = opts.strict
  26. var optKey = opts.key
  27. var optParentKey = opts.parentKey
  28. var optChildren = opts.children
  29. var optSortKey = opts.sortKey
  30. var optReverse = opts.reverse
  31. var optData = opts.data
  32. var result = []
  33. var treeMap = {}
  34. var idList, id, treeData, parentId
  35. if (optSortKey) {
  36. array = orderBy(clone(array), optSortKey)
  37. if (optReverse) {
  38. array = array.reverse()
  39. }
  40. }
  41. idList = map(array, function (item) {
  42. return item[optKey]
  43. })
  44. each(array, function (item) {
  45. id = item[optKey]
  46. if (optData) {
  47. treeData = {}
  48. treeData[optData] = item
  49. } else {
  50. treeData = item
  51. }
  52. parentId = item[optParentKey]
  53. treeMap[id] = treeMap[id] || []
  54. treeMap[parentId] = treeMap[parentId] || []
  55. treeMap[parentId].push(treeData)
  56. treeData[optKey] = id
  57. treeData[optParentKey] = parentId
  58. treeData[optChildren] = treeMap[id]
  59. if (!optStrict || (optStrict && !parentId)) {
  60. if (!includes(idList, parentId)) {
  61. result.push(treeData)
  62. }
  63. }
  64. })
  65. if (optStrict) {
  66. strictTree(array, optChildren)
  67. }
  68. return result
  69. }
  70. module.exports = toArrayTree