-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrie.js
80 lines (68 loc) · 1.18 KB
/
trie.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Created by showzyl on 2017/8/17.
*
* https://github.com/LeuisKen/leuisken.github.io/issues/2
*
* trie树
*
*/
'use strict'
let aResData = [{
val: '浙江',
children: [{
val: '杭州',
children: [{
val: '西湖'
}]
}]
}, {
val: '四川',
children: [{
val: '成都',
children: [{
val: '锦里'
}, {
val: '方所'
}]
}]
}]
let data = [{
pro: '浙江',
city: '杭州',
name: '西湖'
}, {
pro: '四川',
city: '成都',
name: '方所'
}, {
pro: '四川',
city: '成都',
name: '锦里'
}]
let keys = ['pro', 'city', 'name']
let transObject = function(tableData, keys) {
let hashTable = {}, res = []
for (let i = 0; i < tableData.length; i++) {
let arr = res, cur = hashTable
for (let j = 0; j < keys.length; j++) {
let key = keys[j], filed = tableData[i][key]
if (!cur[filed]) {
let pusher = {
value: filed
}, tmp
if (j !== (keys.length - 1)) {
tmp = []
pusher.children = tmp
}
cur[filed] = { $$pos: arr.push(pusher) - 1 }
cur = cur[filed]
arr = tmp
} else {
cur = cur[filed]
arr = arr[cur.$$pos].children
}
}
}
return res
}
console.log('test: ', transObject(data, keys))