需求如题,首先后台给了个对象,要转为数组,
{
"Body": {
"Revenue": {
"Date": "2018-08-24",
"Parking_Code": "GTC001",
"Parking_Name": "GTC停车场",
"Channel_Name": "A01",
"Order_Count": "100",
"Receivable": "100000",
"Receipts": "100000"
}
}
}
处理为el-tree可以识别的数组形式;
// 数据格式化(复杂对象转数组)
objToArr(obj) {
const arr = [];
if (_.isObject(obj)) {
for (var i in obj) {
var oo = {
label: i,
id: this.id++,
children: this.objToArr(obj[i])
};
arr.push(oo);
}
}
return arr;
},
需求是选中某几个后,在返回回去一个对象;
el-tree貌似还没有直接返回选中数组的api,这里采用全选和半选节点的api组合,并通过递归筛选出所需id;
const tree = this.$refs.tree;
const current = tree.getCheckedKeys().concat(tree.getHalfCheckedKeys());
console.log('current', current);
// 递归获取选中数据的数组,包含半选节点;
// let handleList = [];
const saveTreeData = _.cloneDeep(this.treeData);
const handleDataList = list => {
for (let i = 0; i < list.length; i++) {
const item = list[i];
if (item.children) {
handleDataList(item.children);
}
if (!current.includes(item.id)) {
list.splice(i, 1);
i -= 1;
}
}
};
handleDataList(saveTreeData);
console.log('saveTreeData', saveTreeData);
处理完的结果如下:
[
{
"label": "Body",
"id": 1,
"children": [
{
"label": "Revenue",
"id": 2,
"children": [
{
"label": "Parking_Name",
"id": 5,
"children": []
},
{
"label": "Channel_Name",
"id": 6,
"children": []
}
]
}
]
}
]
最后转为对象在传回去:
const obj = {};
// 处理为对象形式;
const handleObj = (dataList, inObj) => {
dataList.forEach(item => {
// 首次进来是obj,即obj[Body] = {},
// 第二次其实是 obj[Body]进来了,所以是obj.Body[Revenue]={}
// 第三次是obj[Body][Revenue]进来了,进而obj[Body][Revenue][Channel_Name] = {}
inObj[item.label] = {};
if (item.children && item.children.length) {
handleObj(item.children, inObj[item.label]);
}
});
};
handleObj(saveTreeData, obj);
console.log('obj', obj);
处理结果:
{
"Body": {
"Revenue": {
"Parking_Name": {},
"Channel_Name": {}
}
}
}
仅以此文,祭奠我逝去的递归小白身份;
有个小技巧,递归里边forEach和for 貌似比es6的map filter好使一点,毕竟是地址调用,子数据进入下一层级 地址不变的情况下 处理完更容易懂一点。