var str = `北京 2
河北 3
河北-邯郸 301
河北-保定 302
河北-邢台 303
山东 4
山东-青岛 401
山东-烟台 402`;
var arrStr = str.split("\n");
var result = [];
arrStr.map(i => {
let = item = i.split(" ");
if (i.indexOf("-") == -1) {
result.push({
label: item[0],
value: item[1],
key: item[1],
children: []
})
} else {
let city = item[0].split("-");
let cur = result.find(j => j.label == city[0])
cur.children.push({
label: city[1],
value: item[1],
key: item[1],
})
}
})
console.log(result)
console.log(JSON.stringify(result))
原文:http://www.cnblogs.com/Smina/p/7208952.html