1.后端返回的数据
"data": [
{
"id": 1,
"pid": 0,
"title": "家具",
"children": [
{
"id": 6,
"pid": 1,
"title": "实木床"
},
{
"id": 7,
"pid": 1,
"title": "气垫床"
}
]
},
{
"id": 2,
"pid": 0,
"title": "家电",
"children": [
{
"id": 3,
"pid": 2,
"title": "电视机"
},
{
"id": 4,
"pid": 2,
"title": "洗衣机"
},
{
"id": 5,
"pid": 2,
"title": "冰箱"
}
]
}
]
2.uni-data-picker需要的数据结构
items: [{
text: "家具",
value: "1,0",
children: [
{
text: "实木床",
value: "1,1"
},
{
text: "气垫床",
value: "1,2"
}
]
}]
3.需要转换的数据:title变为text,id,pid键值拼接,并且键名改为value,例如value:'1,1'
// 将后端返回的树形结构数据修改为uni-ui组件库中uni-data-picker组件需要的树形结构数据,将title字段转换为text字段,将id,pid字段值拼接,键名改为value
transformData(data) {
return data.map(item => {
const {
id,
pid,
title,
children
} = item;
const value = `${pid},${id}`;
const text = title;
const transformedItem = {
text,
value
};
if (children && children.length > 0) {
transformedItem.children = this.transformData(children);
}
return transformedItem;
});
},