1. 一维数组转成嵌套数组(递归)
export let treeClassList = (array) => {
let temp = {}
let tree = {}
console.log('array',array)
array.forEach(item => {
temp[item.ID] = item
})
let tempKeys = Object.keys(temp)
tempKeys.forEach(key => {
let item = temp[key]
let _itemPId = item.Parent_ID
console.log('item',item)
let parentItemByPid = temp[_itemPId]
if (parentItemByPid) {
if (!parentItemByPid.children) {
parentItemByPid.children = []
}
parentItemByPid.children.push(item)
} else {
tree[item.ID] = item
}
})
return Object.keys(tree).map(key => tree[key])
}
2.二维数组转成一维数组 (递归)
var arr = [1, [2, [3, 4]]]
function flatten(arr) {
var result = []
for (var i = 0, len = arr.length; i < len; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]))
} else {
result.push(arr[i])
}
}
return result
}
console.log(flatten(arr))
|