preface
In our work, we may encounter the need for infinite levels of classification and so on. Often the data structure returned by the back end may not be the data structure we want, so let’s see how to deal with it
Flat data structures are converted into JSON tree structures
Let flatArr = [{id: 1, title: "中 国 家 有 关 系 ", parent_id: 0}, {id: 2, title:" 中 国 家 有 关 系 ", parent_id: 0}, {id: 3, title: "中 国 家 有 关 系 ", parent_id: 0}, {id: 3, title:" 中 国 家 有 关 系 ", parent_id: 0}, {id: 3, title: ", parent_id: 2}, {id: 4, title: "parent_id: 3}, {id: 5, title:" parent_id: 4}, {id: 5, title: "parent_id: 4}, {id: 5, title:" parent_id: 4}, {id: 5 Parent_id: 2},]Copy the code
code
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);
Copy the code
The output
Let JsonTree = [{id: 1, children: 1', pid: 0}, {id: 2, children: 1', children: 0}, let JsonTree = [{id: 1, children: 1', children: 0}, children: 1', children: 1', children: 0} Pid: 2}, {id: 3, id: 2, children: [{id: 4, id: 3, children: 3}, {id: 4, id: 3, children: 3}, {id: 4, id: 3, children: 3}, {id: 4, id: 3, children: 3}, {id: 4, id: 3, children: 3}, [{id: 5, the title: 'melancholy grocery 4-1, pid, 4},]},]}}];Copy the code
JSON tree conversion flat structure
We already have the transformed JSON tree structure above, so how do we push it back
code
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)
Copy the code
The output
[{id: 1, the title: 'melancholy grocery store 1, pid: 0}, {id: 2, the title:' melancholy grocery store 2, pid: 0}, {id: 3, the title: 'melancholy grocery 2-1, pid, 2}, {id: Melancholy grocery store 3-4, the title: '1', pid, 3}, {id: 5, the title: 'melancholy grocery 4-1, pid, 4}, {id: 6, the title:' melancholy grocery 4-2, pid, 2},]Copy the code
conclusion
Using the above code, we can easily convert these two data structures ~ if the big guys have a better method, I hope we can discuss together ~