mapTree.js 1.0 KB

123456789101112131415161718192021222324252627282930
  1. var helperCreateTreeFunc = require('./helperCreateTreeFunc')
  2. var map = require('./map')
  3. function mapTreeItem (parent, obj, iterate, context, path, node, parseChildren, opts) {
  4. var paths, nodes, rest
  5. var mapChildren = opts.mapChildren || parseChildren
  6. return map(obj, function (item, index) {
  7. paths = path.concat(['' + index])
  8. nodes = node.concat([item])
  9. rest = iterate.call(context, item, index, obj, paths, parent, nodes)
  10. if (rest && item && parseChildren && item[parseChildren]) {
  11. rest[mapChildren] = mapTreeItem(item, item[parseChildren], iterate, context, paths, nodes, parseChildren, opts)
  12. }
  13. return rest
  14. })
  15. }
  16. /**
  17. * 从树结构中指定方法后的返回值组成的新数组
  18. *
  19. * @param {Object} obj 对象/数组
  20. * @param {Function} iterate(item, index, items, path, parent, nodes) 回调
  21. * @param {Object} options {children: 'children'}
  22. * @param {Object} context 上下文
  23. * @return {Object/Array}
  24. */
  25. var mapTree = helperCreateTreeFunc(mapTreeItem)
  26. module.exports = mapTree