操作数据
jsonArr = [ {
"departmentId": "1",
"name": "中国",
"departmentList": [
{
"departmentId": "49",
"name": "湖南",
"departmentList": [
{
"departmentId": "50",
"name": "娄底",
"departmentList": [
{
"departmentId": "54",
"name": "双峰",
"departmentList": []
}
]
},
{
"departmentId": "51",
"name": "长沙",
"departmentList": []
},
{
"departmentId": "74",
"parentId": "49",
"name": "湘潭",
"departmentList": []
}
]
},
{
"departmentId": "2",
"name": "北京市",
"departmentList": [
{
"departmentId": "5",
"name": "海淀",
"departmentList": []
},
{
"departmentId": "4",
"name": "朝阳",
"departmentList": []
},
{
"departmentId": "12",
"name": "通州",
"departmentList": []
}
]
},
{
"departmentId": "11",
"name": "重庆",
"departmentList": []
},
{
"departmentId": "3",
"name": "黑龙江",
"departmentList": [
{
"departmentId": "7",
"name": "哈尔滨",
"departmentList": []
}
]
}
]
}]
// 将上面的数据每一个数组元素添加一个strName字段,对应值是 ‘国/省/市/县’格式
connectName(arr, str=''){
arr.map((item) => {
item.strName = `${str}${item.name}`
if(item.departmentList.length){
const addstr = `${item.strName}/`
this.connectName(item.departmentList, addstr)
}
})
return arr
},
// 调用
connectName(jsonArr)
// 每一级的对象会包含strName字段, 如第一阶梯会有strName:"中国/湖南/娄底/双峰"
console.log(connectName(jsonArr))
image.png
网友评论