UNPKG

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