实现思路
1. 定义一个新的数组,用于存放去重后的json数组
2. for循环对比每组object,如果不同就push进新数组
源码展示
// 比较两组 json 是否相同 ifCompare(object1, object2) { var o1keys = Object.keys(object1) var o2keys = Object.keys(object2) if (o2keys.length !== o1keys.length) return false for (let i = 0; i < o1keys.length; i++) { const key = o1keys[i] if (!o2keys.includes(key)) return false if (object2[key] !== object1[key]) return false } return true } // json数组去重 let arrayNew = [] const jsonArray = [{ a1: 'a', a2: 'c' }, { a1: 'a', a2: 'b', a3: 'c' }, { a1: 'a', a2: 'c' }, { a2: 'c', a1: 'a' }] if (jsonArray.length > 0) { arrayNew = [jsonArray[0]] for (let i = 0; i < jsonArray.length; i++) { var flag = false for (let j = 0; j < arrayNew.length; j++) { if (this.ifCompare(jsonArray[i], arrayNew[j])) { flag = true } } if (!flag) { arrayNew.push(jsonArray[i]) } } } console.log('jsonArray', jsonArray) console.log('arrayNew', arrayNew)
代码分析