searchTree.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var helperCreateTreeFunc = require('./helperCreateTreeFunc')
  2. var arrayEach = require('./arrayEach')
  3. var assign = require('./assign')
  4. function searchTreeItem (parentAllow, parent, obj, iterate, context, path, node, parseChildren, opts) {
  5. var paths, nodes, rest, isAllow, hasChild
  6. var rests = []
  7. var hasOriginal = opts.original
  8. var sourceData = opts.data
  9. var mapChildren = opts.mapChildren || parseChildren
  10. arrayEach(obj, function (item, index) {
  11. paths = path.concat(['' + index])
  12. nodes = node.concat([item])
  13. isAllow = parentAllow || iterate.call(context, item, index, obj, paths, parent, nodes)
  14. hasChild = parseChildren && item[parseChildren]
  15. if (isAllow || hasChild) {
  16. if (hasOriginal) {
  17. rest = item
  18. } else {
  19. rest = assign({}, item)
  20. if (sourceData) {
  21. rest[sourceData] = item
  22. }
  23. }
  24. rest[mapChildren] = searchTreeItem(isAllow, item, item[parseChildren], iterate, context, paths, nodes, parseChildren, opts)
  25. if (isAllow || rest[mapChildren].length) {
  26. rests.push(rest)
  27. }
  28. } else if (isAllow) {
  29. rests.push(rest)
  30. }
  31. })
  32. return rests
  33. }
  34. /**
  35. * 从树结构中根据回调查找数据
  36. *
  37. * @param {Object} obj 对象/数组
  38. * @param {Function} iterate(item, index, items, path, parent, nodes) 回调
  39. * @param {Object} options {children: 'children'}
  40. * @param {Object} context 上下文
  41. * @return {Array}
  42. */
  43. var searchTree = helperCreateTreeFunc(function (parent, obj, iterate, context, path, nodes, parseChildren, opts) {
  44. return searchTreeItem(0, parent, obj, iterate, context, path, nodes, parseChildren, opts)
  45. })
  46. module.exports = searchTree