数据处理
思路: 1.先创建必要的函数: 数组打平flat,递归树(deepTree),模板(temp) 2.发送数据:首先把你选择的数据格式, deepTreeData(tree, flat(selectedTree), [‘id’]) 选择的数据格式, 3.然后转换成发送的格式, sendSelectedData(tree, flat(selectedTree), [‘id’, ‘name’]) 4.回填数据:把发送的数据打平, splitArr(sendSelectedData(tree, flat(selectedTree)), [‘id’] 5.转换成选中的格式 deepTreeData(tree, flat(selectedTree), [‘id’])
方法一:
let tree = [{
id: 1,
name: "测试",
children: [{
id: 11,
name: '测试11',
children: [{
id: 11113,
name: '测试11'
},
{
id: 11111113,
name: '测试12'
}
]
},
{
id: 12,
name: '测试12'
}
]
},
{
id: 2,
name: "测试",
children: [{
id: 21,
name: '测试21'
},
{
id: 22,
name: '测试22'
}
]
}
]
let selectedTree = [
[1, 11, 12, 11111113, 11113],
[2, 21]
]
console.log("-------------原始全部数据-----------------")
console.log(tree)
console.log("-------------选中原始数据-----------------")
console.log(selectedTree)
function flat(tree) {
if (!Array.isArray(tree)) return
return tree.flat(Infinity)
}
console.log("-------------选中的数据打平-----------------")
console.log(flat(selectedTree))
function temp(arr, data) {
let copyObj = {}
if (arr.length > 1) {
arr.forEach(item => {
copyObj[item] = data[item]
})
return copyObj
} else {
return data[arr[0]]
}
}
var copySelected = []
function deepTree(tree, selectedTree, arr = ['id', 'name']) {
tree.forEach(item => {
selectedTree.includes(item.id) ? copySelected.push(temp(arr, item)) : ''
if (item.children) {
deepTree(item.children, selectedTree, arr)
}
});
}
function deepTreeData(tree, selectedTree, arr = ['id', 'name']) {
let selected = []
tree.forEach(item => {
copySelected = []
selectedTree.includes(item.id) ? copySelected.push(temp(arr, item)) : ''
deepTree(item.children, selectedTree, arr)
selected.push([...copySelected])
})
return selected
}
function sendSelectedData(tree, selectedTree, arr1) {
let copyData = []
let data = deepTreeData(tree, selectedTree, arr1)
data.forEach(item => {
item.forEach(innerItem => {
copyData.push(innerItem)
})
})
return copyData
}
console.log("-------------要发送的数据-----------------")
console.log(sendSelectedData(tree, flat(selectedTree), ['id', 'name']))
function splitArr(data, id) {
return data.map(item => {
return item[id]
})
}
console.log("-------------回填数据打平-----------------")
console.log(splitArr(sendSelectedData(tree, flat(selectedTree)), ['id']))
console.log("-------------渲染数据-----------------")
let arr = deepTreeData(tree, flat(selectedTree), ['id'])
console.log((arr))
方法二:
let str = '12###234,34###345'
let strArr = [
[1, 2],
[4, 5]
]
function splitArr(dataStr) {
let strCopy = dataStr.split(',')
return strCopy = strCopy.map(item => {
return item.split('###')
});
}
function splitStr(dataArr) {
let dataArrCopy = ''
dataArr.map(item => {
const innerStr = item.join('###')
dataArrCopy+=','+innerStr
})
return dataArrCopy.slice(1)
}
console.log(splitArr(str))
console.log(splitStr(strArr))
|