<script>
var arr = [
['广东省',
'广州市',
'天河区'
],
['广东省',
'广州市',
'白云区'
],
[
'广东省',
'东莞市',
'常平镇'
],
];
function toTree(arr) {
const obj = {};
const res = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
const item = arr[i][j];
if (!obj[item]) {
obj[item] = {
name: item,
child: [],
};
}
if (j > 0) {
const parent = obj[arr[i][j - 1]];
if (parent) {
if (parent.child.indexOf(obj[item]) < 0) {
parent.child.push(obj[item]);
}
}
} else {
if (res.indexOf(obj[item]) < 0) {
res.push(obj[item]);
}
}
}
}
return res;
}
console.log(toTree(arr))
</script>
效果图