现在有一个这样的数据
- 江西
– 南昌
– 九江 - 上海
– 航头 - 北京
– 天安门
– 故宫
– 王府井
这样类似的数据
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210702162642377.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hhb3NpY3g=,size_16,color_FFFFFF,t_70)
要处理成这样的数据
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210702162720331.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hhb3NpY3g=,size_16,color_FFFFFF,t_70)
makeData(list, upArray, dataSource) {
dataSource.forEach((item) => {
const array = [...upArray, item.id];
list.push(array);
if (item.children) {
this.makeData(list, array, item.children);
}
});
}
let list = []
this.makeData(list, [], result.data);
根据子级类型查找所有匹配的父级类型
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210702162927389.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hhb3NpY3g=,size_16,color_FFFFFF,t_70)
- 如果当前可以获得最后子级的id ( 选择后发给后端了 后端返回回来的 )
- 但是为了回显 需要获得一串父级的id 类似如下数据
- 6002是子级的 需要拿到从最父级的一直到最子级的数组
- 如果拿到一串很多最子级的id的数据 也可以通过这个方法来处理
getFathersById(id, data, prop = 'id') {
const arrRes = [];
const rev = (data, nodeId) => {
for (let i = 0, length = data.length; i < length; i++) {
const node = data[i];
if (node[prop] === nodeId) {
arrRes.unshift(node[prop]);
return true;
} else {
if (node.children && node.children.length) {
if (rev(node.children, nodeId)) {
arrRes.unshift(node[prop]);
return true;
}
}
}
}
return false;
};
rev(data, id);
return arrRes;
},
LabeList.forEach(item => {
arr.push(this.getFathersById(item, options));
});