const arr = [
[10000, 10001, 10067, 10068],
[10000, 10001, 10069],
[10000, 10003, 10071],
[10004, 10006, 10075]
]
先处理一遍数据,放进objList里,其中每一个对象都有它的pid,并去重,以便后续处理
let idList = []
let objList = []
arr.forEach(item => {
item.forEach((ite, ind) => {
// console.log(ite);
if (!idList.includes(ite)) {
let obj = {
id: ite,
pid: ind == 0 ? 0 : item[ind - 1]
}
objList.push(obj)
idList.push(ite)
}
})
})
处理后objList的结果

方法二处理一遍搞定
function toTree(data) {
let result = []
if (!Array.isArray(data)) {
return result
}
data.forEach(item => {
delete item.children;
});
let map = {};
data.forEach(item => {
map[item.id] = item;
});
data.forEach(item => {
let parent = map[item.pid];
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
result.push(item);
}
});
return result;
}
console.log(toTree(objList))

文章讲述了如何使用JavaScript处理二维数组,将数据放入objList并去除重复id。首先通过遍历实现基础处理,然后使用toTree函数构建树形结构,该函数通过映射关系将数据组织为树结构。
1265

被折叠的 条评论
为什么被折叠?



