-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.js
92 lines (81 loc) · 1.85 KB
/
convert.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
* File: convert china address data
* Author: jakexchan
*/
const fs = require('fs');
const cmder = require('commander');
const package = require('./package.json');
cmder
.version(package.version)
.option('-s, --source <path>', 'Data source')
.option('-o, --output <path>', 'Output')
.parse(process.argv);
main();
function main () {
fs.readFile(cmder.source, 'utf-8', (err, data) => {
if (err) {
throw new Error(err);
}
let address = JSON.parse(data);
let result = treeToList(convertToTree(address));
fs.writeFile(cmder.output, JSON.stringify(result, null, 2), 'utf-8', (err, data) => {
if (err) {
throw new Error(err);
}
console.log('Convert success!');
})
});
}
/**
* List to tree
*
* @param {array} data
* @returns {object}
*/
function convertToTree (data) {
let obj = {};
for (let i = 0; i < data.length; i++) {
let current = data[i];
if (typeof current.parent === 'undefined') {
obj[current.value] = {
value: current.value,
label: current.name,
children: {}
}
} else {
if (obj[current.parent]) {
obj[current.parent].children[current.value] = {
value: current.value,
label: current.name,
children: {}
}
} else {
for (let key in obj) {
if (obj[key].children[current.parent]) {
obj[key].children[current.parent].children[current.value] = {
value: current.value,
label: current.name
}
}
}
}
}
}
return obj;
}
/**
* Tree to list
*
* @param {object} data
* @returns
*/
function treeToList (data) {
let array = [];
for (let key in data) {
if (data[key].children) {
data[key].children = treeToList(data[key].children);
}
array.push(data[key]);
}
return array;
}