const data = [
{ province: "广东省", city: "广州市", district: "天河区" },
{ province: "广东省", city: "广州市", district: "白云区" },
{ province: "广东省", city: "东莞市", district: "石龙镇" },
]
function bbb(data, keys, keyVals = []) {
let arr = []
for (let i = 0; i < data.length; i++) {
let index = 0
for (let k = 0; k < keyVals.length; k++) {
const key = keys[k]
if (data[i][key] === keyVals[k]) {
index = k + 1
}
}
let test = data[i][keys[index]]
if ((index == 0 || index == keyVals.length) && arr.findIndex((c) => c.name === data[i][keys[index]]) === -1) {
let newKeyVals = [].concat(keyVals)
newKeyVals.push(data[i][keys[index]])
arr.push({
name: data[i][keys[index]],
children: keys.length === newKeyVals.length ? [] : bbb(data, keys, newKeyVals),
})
}
}
return arr
}
let cc = bbb(data, ["province", "city", "district"])
console.log(JSON.stringify(cc))
console