先上代码
const data = [
{ id: 4, title: '测试标题4', parent: 2 },
{ id: 1, title: '测试标题1', parent: null },
{ id: 8, title: '测试标题8', parent: 3 },
{ id: 2, title: '测试标题2', parent: null },
{ id: 11, title: '测试标题11', parent: 4 },
{ id: 12, title: '测试标题12', parent: 4 },
{ id: 5, title: '测试标题5', parent: 3 },
{ id: 3, title: '测试标题3', parent: 1 },
{ id: 9, title: '测试标题9', parent: 4 },
{ id: 6, title: '测试标题6', parent: 3 },
{ id: 10, title: '测试标题10', parent: 4 },
{ id: 7, title: '测试标题7', parent: 3 },
];
const mapping = {};
for (let i = 0; i < data.length; i++) {
const element = data[i];
mapping[element.id] = element;
element.children = [];
}
const Tree = [];
for (const key in mapping) {
const element = mapping[key];
// 输出结果
console.log(element.id, element.title);
if (mapping[element.parent]) {
mapping[element.parent].children.push(element);
} else {
Tree.push(element);
}
}
数据结果
1 '测试标题1' index.js:66
2 '测试标题2' index.js:66
3 '测试标题3' index.js:66
4 '测试标题4' index.js:66
5 '测试标题5' index.js:66
6 '测试标题6' index.js:66
7 '测试标题7' index.js:66
8 '测试标题8' index.js:66
9 '测试标题9' index.js:66
10 '测试标题10' index.js:66
11 '测试标题11' index.js:66
12 '测试标题12' index.js:66
会不会觉得很奇怪?列表明明是乱序的,为什么数据的数据这么和谐?
当这个列表有顺序要求的时候,这个格式化的方法,就已经完全不好用了。。
(遇到这个BUG是因为写菜单栏,这个菜单的顺序并不是按照 id 的顺序来的,而是更新时间的顺序来的)
先给解决办法
// ......
const mapping = {};
for (let i = 0; i < data.length; i++) {
const element = data[i];
mapping[element.id + 'A'] = element;
element.children = [];
}
const Tree = [];
for (const key in mapping) {
const element = mapping[key];
// 输出结果
console.log(element.id, element.title);
if (mapping[element.parent + 'A']) {
mapping[element.parent + 'A'].children.push(element);
} else {
Tree.push(element);
}
}
实际上就是在 数组转对象的时候,可以被转换为数字的值会被强制转成数字,并按照数字重新排序
('1','2' 这种可以转换为数字的也不行)
解决办法也很简单,就是在 数组转对象的时候,让字符串转不了数字就可以了!这样就可以不用重新排序了