对象去重的几种方法

时间:2024-01-22 22:14:00

对象数组去重呢,不像数组去重那么简单,但是思想和数组去重类似,下面简单的说一下对象数组去重的一些思想,

对象数组去重呢,就是循环这个数组对象两次,判断每一个对象和每一个对象的某个属性值是否相同,大致的思想就是这样,废话不多说,直接上代码:

 

<script src="../../../../../../../ios/jquery.min.js"></script>
<script>
//需求:把数组里面每个对象里面id相同的去除
//原生js
//原数据数组
var oldArr = [
{ id: 1, name: "zhangs", age: 18, contact_id: 1 },
{ id: 1, name: "zhangs", age: 18, contact_id: 2 },
{ id: 3, name: "zhangs", age: 18, contact_id: 3 },
{ id: 4, name: "zhangs", age: 18, contact_id: 14 },
{ id: 1, name: "zhangs", age: 18, contact_id: 3 },
{ id: 6, name: "zhangs", age: 18, contact_id: 2 },
{ id: 7, name: "zhangs", age: 18, contact_id: 1 }
];
for (var i = 0; i < oldArr.length; i++) {
// 不需要自己和自己比较,比较过的不需要相比较
for (var j = i + 1; j < oldArr.length; j++) {
console.log(i, j, 'ok');
if (oldArr[i].id == oldArr[j].id) {
console.log(i, j);
oldArr.splice(j, 1);
}
}
}
console.log(oldArr);
// 第二种方法
var oldArr2 = [
{ id: 1, name: "zhangs", age: 18, contact_id: 1 },
{ id: 1, name: "zhangs", age: 18, contact_id: 2 },
{ id: 3, name: "zhangs", age: 18, contact_id: 3 },
{ id: 4, name: "zhangs", age: 18, contact_id: 14 },
{ id: 1, name: "zhangs", age: 18, contact_id: 3 },
{ id: 6, name: "zhangs", age: 18, contact_id: 2 },
{ id: 7, name: "zhangs", age: 18, contact_id: 1 }
];
var empty = [];
for (var i = 0; i < oldArr2.length; i++) {
var cp = true;
for (var j = i + 1; j < oldArr2.length; j++) {
if (oldArr2[i].id == oldArr2[j].id) {
cp = false;
}
}
if (cp) {
empty.push(oldArr2[i]);
}
}
console.log(empty);
// jq的方法
var oldArr = [
{ id: 1, name: "zhangs", age: 18, contact_id: 1 },
{ id: 2, name: "zhangs", age: 18, contact_id: 2 },
{ id: 3, name: "zhangs", age: 18, contact_id: 3 },
{ id: 4, name: "zhangs", age: 18, contact_id: 14 },
{ id: 1, name: "zhangs", age: 18, contact_id: 3 },
{ id: 4, name: "zhangs", age: 18, contact_id: 2 },
{ id: 1, name: "zhangs", age: 18, contact_id: 1 }
];
var allArr = []; //新数组
$.each(oldArr, function(i, v) {
var flag = true;
if (allArr.length > 0) {
$.each(allArr, function(n, m) {
if (allArr[n].id == oldArr[i].id) { flag = false; };
});
};
// 第一次allArr是空的,经过这个操作使得allArr有了新数据
if (flag) {
allArr.push(oldArr[i]);
};
});
console.log(allArr);

</script>