JSON
[
{id: 22, parent: “-1”, text: “酒”}
{id: 23, parent: “22”, text: “白酒”}
{id: 24, parent: “22”, text: “红酒”}
{id: 25, parent: “22”, text: “洋酒”}
{id: 26, parent: “22”, text: “香槟”}
{id: 27, parent: “22”, text: “药酒”}
{id: 28, parent: “22”, text: “麦卡伦”}
]
重组
const treeArr: any[] = [];
response.Message.unshift({ id: '' });
const reducetreeArr = response.Message.reduce(
(_prev: any, val: { parent: string | string[] }, idx: any, arr: any) => {
if (val.parent.includes('-1')) {
treeArr.push({
...val,
children: [...arr],
});
}
return treeArr;
},
);
const filterTreeChildren: any[] = [];
reducetreeArr.forEach(
(value: { children: any[]; id: number }, idx: string | number) => {
filterTreeChildren[idx] = value;
filterTreeChildren[idx].children = value.children.filter(
(element) => Number(element.parent) === value.id,
);
},
);
filterTreeChildren.forEach((items) => {
const cachFieldItems = items;
cachFieldItems.title = items.text;
cachFieldItems.key = items.id;
items.children.forEach(
(element: {
title: string;
text: string;
key: number | string;
id: number | string;
}) => {
const cachField = element;
cachField.title = element.text;
cachField.key = element.id;
},
);
});
filterTreeChildren.forEach((items) => {
if (items.children.length === 0) {
const cachField = items;
delete cachField.children;
}
});
const treeArray = [
{
title: '全部数据',
key: '0',
id: 0,
children: filterTreeChildren,
},
];