JavaScript 树形结构数据转换错误分析与解决
在将扁平数组转换为树形结构时,经常需要遍历数组并根据父子关系进行分组。本文将以一个具体的例子来分析常见的错误,并提供解决方案。
代码示例:
const arrayData = [
{ id: 2, title: '中国', parentid: 0 },
{ id: 3, title: '广东省', parentid: 2 },
{ id: 4, title: '广州市', parentid: 3 },
{ id: 5, title: '天河区', parentid: 4 },
{ id: 6, title: '湖南省', parentid: 2 },
{ id: 1, title: '俄罗斯', parentid: 0 }
]
function treelist(arr,pid=0){
let arry = []
arr.forEach(item=>{
if(item.parentid=pid){
let obj = {
id:item.id,
title:item.title,
children:treelist(arr,item.id)
}
arry.push(obj)
}
})
return arry
}
console.log(treelist(arrayData));
错误分析:
在条件判断中,应该使用双等号(==)或者三等号(===)来判断相等性,而不是单等号(=)赋值。所以在if(item.parentid=pid)这一行,应该改为if(item.parentid === pid)。
解决方案:
将条件判断中的=改为===,修改后的代码如下:
const arrayData = [
{ id: 2, title: '中国', parentid: 0 },
{ id: 3, title: '广东省', parentid: 2 },
{ id: 4, title: '广州市', parentid: 3 },
{ id: 5, title: '天河区', parentid: 4 },
{ id: 6, title: '湖南省', parentid: 2 },
{ id: 1, title: '俄罗斯', parentid: 0 }
]
function treelist(arr,pid=0){
let arry = []
arr.forEach(item=>{
if(item.parentid === pid){
let obj = {
id:item.id,
title:item.title,
children:treelist(arr,item.id)
}
arry.push(obj)
}
})
return arry
}
console.log(treelist(arrayData));
总结:
使用===来判断相等性是 JavaScript 中的最佳实践,可以避免因类型转换带来的意外结果。在进行条件判断时,一定要仔细检查操作符,确保使用正确的符号。
原文地址: https://www.cveoy.top/t/topic/qqpz 著作权归作者所有。请勿转载和采集!