前言
在工作中我们往往可能会遇到无限级别的分类等等的需求,往往后端返回的数据结构可能不是我们想要的数据结构,所以我们来看怎么进行处理
扁平数据结构转换为JSON树型结构
let flatArr = [
{id: 1, title: "解忧杂货铺1", parent_id: 0},
{id: 2, title: '解忧杂货铺2', parent_id: 0},
{id: 3, title: '解忧杂货铺2-1', parent_id: 2},
{id: 4, title: '解忧杂货铺3-1', parent_id: 3},
{id: 5, title: '解忧杂货铺4-1', parent_id: 4},
{id: 6, title: '解忧杂货铺2-2', parent_id: 2},
]
代码
function convert(list) {
const res = [];
const map = list.reduce((res, v) => (res[v.id] = v, res), {});
for (const item of list) {
if (item.parent_id === 0) {
res.push(item);
continue;
}
if (item.parent_id in map) {
const parent = map[item.parent_id];
parent.children = parent.children || [];
parent.children.push(item);
}
}
return res;
}
let returnTree = convert(flatArr);
console.log(returnTree);
输出结果
let JsonTree = [
{id: 1, title: '解忧杂货铺1', pid: 0},
{
id: 2, title: '解忧杂货铺2', pid: 0, children: [
{id: 6, title: '解忧杂货铺4-2', pid: 2},
{
id: 3, title: '解忧杂货铺2-1', pid: 2, children: [
{
id: 4, title: '解忧杂货铺3-1', pid: 3, children: [
{id: 5, title: '解忧杂货铺4-1', pid: 4},
]
},
]
},
]
}
];
JSON树型结构转换扁平结构
我们看到上面已经有转换好了的JSON树形结构,那么我们如何把上面的结构反推回来呢
代码
function flatten(data) {
return data.reduce((arr, {id, title, pid, children = []}) =>
arr.concat([{id, title, pid}], flatten(children)), []);
}
let flatArr = flatten(JsonTree);
console.log(flatArr)
输出结果
[
{id: 1, title: '解忧杂货铺1', pid: 0},
{id: 2, title: '解忧杂货铺2', pid: 0},
{id: 3, title: '解忧杂货铺2-1', pid: 2},
{id: 4, title: '解忧杂货铺3-1', pid: 3},
{id: 5, title: '解忧杂货铺4-1', pid: 4},
{id: 6, title: '解忧杂货铺4-2', pid: 2},
]
结语
利用上面的代码,我们就可以轻松的转换这两种数据结构~
如果大佬们有更好的方法,希望可以发出来一起探讨~