function deepClone(arr) {
if (arr && typeof arr === 'object') {
const target = arr.constructor === Array ? [] : {}
Object.keys(arr).forEach(key => {
if (arr[key] && typeof arr[key] === 'object') {
target[key] = deepClone(arr[key])
} else {
target[key] = arr[key]
}
})
return target
} else {
throw new Error('参数不是对象或数组')
}
}
function flatArray(arr, newArr = []) {
arr.forEach(item => {
if (item.constructor === Array) {
flatArray(item, newArr)
} else {
newArr.push(item)
}
})
return newArr
}
function listToTree(arr, id = 'id', pId = 'pId', children = 'children') {
const cloneData = deepClone(arr)
return cloneData.filter(father => {
let branchData = cloneData.filter(child => father[id] === child[pId])
branchData.length > 0 ? father[children] = branchData : ''
return father[pId] === 0
})
}
let arr = [
{id: 1, pId: 0, name: '1'},
{id: 2, pId: 1, name: '1-1'},
{id: 3, pId: 2, name: '1-1-1'},
{id: 4, pId: 3, name: '1-1-1-1'}
]
function arrToTreeNew(arr) {
const result = []
const map = {}
arr.forEach(item => {
map[item.id] = item
})
arr.forEach(item => {
const parent = map[item.pid]
if (parent) {
(parent.children || (parent.children = [])).push(item)
} else {
result.push(item)
}
})
return result
}
const arr2 = [
{id: 1, pid: 0, name: 'body'},
{id: 2, pid: 1, name: 'title'},
{id: 3, pid: 1, name: 'div'},
{id: 4, pid: 3, name: 'span'},
{id: 5, pid: 3, name: 'icon '},
{id: 6, pid: 4, name: 'subspan'}
]
function getQueryObject(url) {
url = url || window.location.search
const search = url.substring(url.lastIndexOf('?') + 1)
const obj = {}
const reg = /([^?&=]+)=([^?&=]*)/g
search.replace(reg, (rs, $1, $2) => {
const name = decodeURIComponent($1)
let val = decodeURIComponent($2)
val = String(val)
obj[name] = val
return rs
})
return obj
}
function isObject(params) {
return Object.prototype.toString.call(params) === '[object Object]'
}
function isArray(params) {
return Object.prototype.toString.call(params) === '[object Array]'
}