文本文件格式如下:北京 2河北 3河北-邯郸 301河北-保定 302河北-邢台 303山东 4山东-青岛 401山东-烟台 402转换成类似如下的json,我只要该结果const treeData = [{ label: '河北', value: '3', key: '3', children: [{ label: '邯郸', value: '301', key: '302',
}, { label: '保定', value: '302', key: '302',
}],
}]
1 回答
呼啦一阵风
TA贡献1802条经验 获得超6个赞
没做容错, 格式必须按上面的格式
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))
[ {"label":"北京","value":"2","key":"2","children":[]}, {"label":"河北","value":"3","key":"3","children":[ {"label":"邯郸","value":"301","key":"301"}, {"label":"保定","value":"302","key":"302"}, {"label":"邢台","value":"303","key":"303"} ]}, {"label":"山东","value":"4","key":"4","children":[ {"label":"青岛","value":"401","key":"401"}, {"label":"烟台","value":"402","key":"402"} ]} ]
添加回答
举报
0/150
提交
取消