array.js
2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
*去除数组中的无效值
*
* @export
* @param {any[]} array 要检查的数组
* @return {*} []
*/
export function validArray(array) {
return array.filter(Boolean)
}
/**
*数组对象去重
*
* @export
* @param {any[]} array 要去重的数组
* @param {string} key 要去重的对象属性值
* @return {*} {any[]}
*/
export function uniqueArrayObject(array, key) {
return array.reduce((pre, cur) => {
const keys = pre.map((item) => item[key])
return keys.includes(cur[key]) ? pre : [...pre, cur]
}, [])
}
export function filterQueryList(array, key = 'value') {
return array.filter((item) => item[key])
}
/**
*数组去重
*
* @export
* @param {any[]} array 要检查的数组
* @return {*} []
*/
export function uniqueArr(array) {
return Array.from(new Set(array))
}
export function nest2tile(arr, childrenKey, obtainChildren) {
if (!childrenKey) {
childrenKey = 'children'
}
if (!arr || arr.constructor !== Array) return
return [].concat(
...arr.map((item) => {
let _item = { ...item }
if (obtainChildren == undefined || obtainChildren == false) {
delete _item[childrenKey]
}
return [].concat(_item, ...nest2tile(item[childrenKey] || []))
})
)
}
// 平铺结构转嵌套结构
export function tile2nest(array, key, pKey, childrenKey) {
if (!array || array.constructor !== Array) {
return array
}
// 复制一份,避免修改原始数组
let ary = [...array]
key = key || 'id'
pKey = pKey || 'parentId'
childrenKey = childrenKey || 'children'
// 定义一个待移除数组
let ary2remove = []
ary.map((item) => {
if (item[key] !== item[pKey]) {
// 找父节点
let p = ary.filter((c) => c[key] === item[pKey])
if (p && p.length == 1) {
p[0][childrenKey] = p[0][childrenKey] || []
// 将子节点放到父节点中
p[0][childrenKey].push(item)
ary2remove.push(item[key])
}
}
})
// 遍历移除待删除对象
ary2remove.map((item) => {
ary = ary.filter((c) => c[key] !== item)
})
return ary
}