toTreeArray.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var setupDefaults = require('./setupDefaults')
  2. var arrayEach = require('./arrayEach')
  3. var assign = require('./assign')
  4. function unTreeList (result, parentItem, array, opts) {
  5. var optKey = opts.key
  6. var optParentKey = opts.parentKey
  7. var optChildren = opts.children
  8. var optData = opts.data
  9. var optUpdated = opts.updated
  10. var optClear = opts.clear
  11. arrayEach(array, function (item) {
  12. var childList = item[optChildren]
  13. if (optData) {
  14. item = item[optData]
  15. }
  16. if (optUpdated !== false) {
  17. item[optParentKey] = parentItem ? parentItem[optKey] : null
  18. }
  19. result.push(item)
  20. if (childList && childList.length) {
  21. unTreeList(result, item, childList, opts)
  22. }
  23. if (optClear) {
  24. delete item[optChildren]
  25. }
  26. })
  27. return result
  28. }
  29. /**
  30. * 将一个树结构转成数组列表
  31. *
  32. * @param {Array} array 数组
  33. * @param {Object} options { children: 'children', data: 'data', clear: false }
  34. * @return {Array}
  35. */
  36. function toTreeArray (array, options) {
  37. return unTreeList([], null, array, assign({}, setupDefaults.treeOptions, options))
  38. }
  39. module.exports = toTreeArray