var arr = [
{ text: "广东省", pid: "中国" },
{ text: "江西省", pid: "中国" },
{ text: "广州市", pid: "广东省" },
{ text: "深圳市", pid: "广东省" },
{ text: "罗湖区", pid: "深圳市" },
{ text: "南山区", pid: "深圳市" },
{ text: "首尔", pid: "韩国" },
{ text: "梨泰院", pid: "首尔" },
{ text: "巴黎", pid: "法国" },
{ text: "巴黎市1", pid: "巴黎" },
{ text: "巴黎市2", pid: "巴黎" },
{ text: "东京", pid: "日本" },
];
function isExistPid(obj, record, isParent) {
const { pid } = record;
let str = Object.prototype.toString.call(obj);
let _isExist = false;
if (str === "[object Array]") {
for (let item of obj) {
if (item.text === pid) {
_isExist = true;
if (item.children) {
item.children.push(record);
} else {
item.children = [record];
}
break;
}
if (item.children) {
let { value, isExist } = isExistPid(item.children, record);
_isExist = isExist;
item.children = value;
if (isExist) {
break;
}
}
}
//没有找到并且为父元素直接添加进去
if (!_isExist && isParent) {
obj.push({
text: pid,
pid: pid,
children: [record],
});
}
}
if (str === "[object Object]") {
if (obj.text === pid) {
_isExist = true;
if (obj.children) {
obj.children.push(record);
} else {
obj.children = [record];
}
} else {
if (obj.children) {
let { value, isExist } = isExistPid(item.children, record);
_isExist = isExist;
obj.children = value;
}
}
}
return {
value: obj,
isExist: _isExist,
};
}
var zArr = arr.reduce((arr, nextVal) => {
let { value } = isExistPid(arr, nextVal, true);
return value;
}, []);
console.log(zArr);
递归数组生成国家城市树数据
最新推荐文章于 2024-03-08 11:51:56 发布