js将列表转为树形结构(产品分类)

包含父子级关系的数据列表

let allData = [
  { id: 1, title: 'test1', fatherId: 0, children: [] },
  { id: 2, title: 'test2', fatherId: 1, children: [] },
  { id: 3, title: 'test3', fatherId: 1, children: [] },
  { id: 4, title: 'test4', fatherId: 0, children: [] },
  { id: 5, title: 'test5', fatherId: 4, children: [] },
  { id: 6, title: 'test6', fatherId: 4, children: [] }
]

转树形方式1:

let nodeMap = {}
allData.forEach((item) => (nodeMap[item.id] = item))
let data = []
for (const item of allData) {
  if (item.fatherId) {
    let father = nodeMap[item.fatherId]
    if (father) father.children.push(item)
  } else data.push(item)
}

console.log(data)

转树形方式2:

let fatherData = allData.filter((item) => item.fatherId === 0)
const childData = allData.filter((item) => item.fatherId !== 0)
for (const child of childData) {
  for (const father of fatherData) {
    if (child.fatherId === father.id) {
      father.children.push(child)
      break
    }
  }
}
const data = fatherData
console.log(data)

猜你喜欢

转载自blog.csdn.net/qq_41579327/article/details/130461081