对象数组去重
作者:xie392地址:https://v.douyin.com/iemWLVwD/更新时间:2024-12-21
案例代码
1const 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 {*} obj10* @returns11*/12const isObject = (obj) => typeof obj === 'object' && obj !== null1314const newArr = [...arr]15for (let i = 0; i < newArr.length; i++) {16for (let j = i + 1; j < newArr.length; j++) {17if (equals(newArr[i], newArr[j])) {18newArr.splice(j, 1)19j--20}21}22}2324/**25* 对比两个值是否相等26* @param {*} a 对象或字符27* @param {*} b 对象或字符28* @returns29*/30function equals(a, b) {31if(!isObject(a) || !isObject(b)) return Object.is(a, b)32if(a === b) return true33const keysA = Object.keys(a)34const keysB = Object.keys(b)35if(keysA.length !== keysB.length) return false3637for(const key of keysA) {38if(!keysB.includes(key)) return false39const res = equals(a[key], b[key])40if(!res) return false41}42return true43}4445console.log(newArr)
输出结果:
1[2{3"a": 1,4"b": 25},6{7"a": 1,8"b": 2,9"c": {10"a": 1,11"b": 212}13}14]
目录