1. js代码
/**
* list转tree
* @param {Array} array list数组
* @param {String} key 当前主键名称
* @param {String} upKey 上级主键名称
* @param {String} pid 最上级参数值
* @param {String} childKey 子集字段名
*/
export function toTree(array, key, upKey, pid, childKey) {
return new Promise((resolve, reject) => {
const parents = array.filter(x => x[upKey] === pid)
const list = []
parents.forEach(x => {
const data = tree(x, array, key, upKey, list, childKey)
if (data.length > 0) x[childKey] = data
})
resolve(parents)
})
}
export function tree(parent, array, key, upKey, list, childKey) {
const child = []
array.filter(x => !list.includes(x[key]))
.filter(x => parent[key] === x[upKey]).forEach(x => {
list.push(x[key])
child.push(x)
const data = tree(x, array, key, upKey, list, childKey)
if (data.length > 0) x[childKey] = data
})
return child
}
调试:
toTree() {
const data = [
{ unitId: 1, upUnitId: '', unitName: '支队' },
{ unitId: 2, upUnitId: 1, unitName: '一队' },
{ unitId: 3, upUnitId: 1, unitName: '二队' },
{ unitId: 4, upUnitId: 1, unitName: '三队' },
{ unitId: 5, upUnitId: 1, unitName: '四队' },
{ unitId: 6, upUnitId: 2, unitName: '四队' },
{ unitId: 7, upUnitId: 2, unitName: '四队' },
{ unitId: 8, upUnitId: 6, unitName: '四队' },
{ unitId: 9, upUnitId: 6, unitName: '四队' },
{ unitId: 10, upUnitId: '', unitName: '四队' },
{ unitId: 11, upUnitId: 10, unitName: '四队' },
{ unitId: 12, upUnitId: 10, unitName: '四队' },
{ unitId: 13, upUnitId: 10, unitName: '四队' }
]
toTree(data, 'unitId', 'upUnitId', '', 'chriend').then(res => {
console.log(res)
})
}
2. java
@Override
public Object getTree() {
RpsBody rpsBody = new RpsBody();
rpsBody.setCode("-1");
List<RouterTree> list = urRouterMapper.query(new LambdaQueryWrapper<Router>());
System.out.println(list);
List<RouterTree> collect = list.stream().filter(x -> "*".equals(x.getRouterSuper())).collect(Collectors.toList());
list.removeAll(collect);
ArrayList<String> arrayList = new ArrayList<>();
collect.stream().forEach(x->tree(x, list, arrayList));
rpsBody.setCode("200");
rpsBody.setData(collect);
rpsBody.setMessage("操作成功");
return VcResponse.save(rpsBody);
}
void tree(RouterTree family, List<RouterTree> list , ArrayList<String> arrayList) {
if (!family.getLast()) {
List<RouterTree> child = new ArrayList<>();
list.stream()
.filter(x -> !arrayList.contains(x.getRouterId()))
.filter(x-> x.getRouterSuper().equals(family.getRouterId()))
.forEach(x->{
arrayList.add(x.getRouterId());
child.add(x);
tree(x,list,arrayList);
});
family.setChildren(child);
}
}