对象数组去重

作者:xie392地址:https://v.douyin.com/iemWLVwD/更新时间:2024-12-21

案例代码

1
const arr = [
2
{ a: 1, b: 2 },
3
{ b: 2, a: 1 },
4
{ a: 1, b: 2, c: { a: 1, b: 2 } },
5
{ b: 2, a: 1, c: { b: 2, a: 1 } },
6
]
7
/**
8
* 判断是否是对象
9
* @param {*} obj
10
* @returns
11
*/
12
const isObject = (obj) => typeof obj === 'object' && obj !== null
13
14
const newArr = [...arr]
15
for (let i = 0; i < newArr.length; i++) {
16
for (let j = i + 1; j < newArr.length; j++) {
17
if (equals(newArr[i], newArr[j])) {
18
newArr.splice(j, 1)
19
j--
20
}
21
}
22
}
23
24
/**
25
* 对比两个值是否相等
26
* @param {*} a 对象或字符
27
* @param {*} b 对象或字符
28
* @returns
29
*/
30
function equals(a, b) {
31
if(!isObject(a) || !isObject(b)) return Object.is(a, b)
32
if(a === b) return true
33
const keysA = Object.keys(a)
34
const keysB = Object.keys(b)
35
if(keysA.length !== keysB.length) return false
36
37
for(const key of keysA) {
38
if(!keysB.includes(key)) return false
39
const res = equals(a[key], b[key])
40
if(!res) return false
41
}
42
return true
43
}
44
45
console.log(newArr)

输出结果:

1
[
2
{
3
"a": 1,
4
"b": 2
5
},
6
{
7
"a": 1,
8
"b": 2,
9
"c": {
10
"a": 1,
11
"b": 2
12
}
13
}
14
]