findTree.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. var helperCreateTreeFunc = require('./helperCreateTreeFunc')
  2. function findTreeItem (parent, obj, iterate, context, path, node, parseChildren, opts) {
  3. if (obj) {
  4. var item, index, len, paths, nodes, match
  5. for (index = 0, len = obj.length; index < len; index++) {
  6. item = obj[index]
  7. paths = path.concat(['' + index])
  8. nodes = node.concat([item])
  9. if (iterate.call(context, item, index, obj, paths, parent, nodes)) {
  10. return { index: index, item: item, path: paths, items: obj, parent: parent, nodes: nodes }
  11. }
  12. if (parseChildren && item) {
  13. match = findTreeItem(item, item[parseChildren], iterate, context, paths.concat([parseChildren]), nodes, parseChildren, opts)
  14. if (match) {
  15. return match
  16. }
  17. }
  18. }
  19. }
  20. }
  21. /**
  22. * 从树结构中查找匹配第一条数据的键、值、路径
  23. *
  24. * @param {Object} obj 对象/数组
  25. * @param {Function} iterate(item, index, items, path, parent, nodes) 回调
  26. * @param {Object} options {children: 'children'}
  27. * @param {Object} context 上下文
  28. * @return {Object} { item, index, items, path, parent, nodes }
  29. */
  30. var findTree = helperCreateTreeFunc(findTreeItem)
  31. module.exports = findTree