将data1的数据结构转化成data2的数据结构:
const data1 = [
{
"group_id" : "1" ,"group_name" : "广州" ,"p_group_id" : "-1" ,"group_level" : 1 ,
},{
"group_id" : "11" ,"group_name" : "番禺" ,"p_group_id" : "1" ,"group_level" : 2 ,
},{
"group_id" : "12" ,"group_name" : "荔湾" ,"p_group_id" : "1" ,"group_level" : 2 ,
},
{"group_id" : "111" ,"group_name" : "市桥" ,"p_group_id" : "11" ,"group_level" : 3 ,
},
{"group_id" : "1111" ,"group_name" : "银座" ,"p_group_id" : "111" ,"group_level" : 4 ,
},{
"group_id" : "2" ,"group_name" : "杭州" ,"p_group_id" : "-1" ,"group_level" : 1 ,
},{
"group_id" : "21" ,"group_name" : "余杭" ,"p_group_id" : "2" ,"group_level" : 2 ,
},{
"group_id" : "211" ,"group_name" : "海创园" ,"p_group_id" : "21" ,"group_level" : 3 ,
},{
"group_id" : "212" ,"group_name" : "海创园二期" ,"p_group_id" : "21" ,"group_level" : 3 ,
},{
"group_id" : "213" ,"group_name" : "海创园三期" ,"p_group_id" : "21" ,"group_level" : 3 ,
},{
"group_id" : "2131" ,"group_name" : "三期A栋" ,"p_group_id" : "213" ,"group_level" : 4 ,
}
];
const data2 = [
{
value : "1",
label : "广州",
children : [
{
value : "11",
label : "番禺",
children : [
{
value : "111",
label : "市桥“
children : [
{value : "1111",label : "银座"}
]
}
]
}
]
}
]
代码如下:
getGroupData = ( groupList ) => {
let data = []groupList . map (( item , index ) => {
let obj = {}obj . value = item . group_idobj . label = item . group_namelet childList = []this . state . deviceGroupList . map (( item2 , index ) => {
if ( item2 . p_group_id === item . group_id ) {childList . push ( item2 )}
})if ( childList . length > 0 ) {obj . children = this . getGroupData ( childList )}data . push ( obj )//若是顶级分组数据,则直接push到groupOptions数组里if ( item . p_group_id == - 1 ) {this . state . groupOptions . push ( obj )}
})return data
}