从JavaScript中的对象数组中删除重复项我有一个包含对象数组的对象。things = new Object();things.thing = new Array();things.thing.push({place:"here",name:"stuff"});things.thing.push({place:"there",name:"morestuff"});things.thing.push({place:"there",name:"morestuff"});我想知道从数组中删除重复对象的最佳方法是什么。所以,例如,事情会变成......{place:"here",name:"stuff"},{place:"there",name:"morestuff"}
4 回答
一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
让我们看看......一个原始的:
var obj = {};for ( var i=0, len=things.thing.length; i < len; i++ ) obj[things.thing[i]['place']] = things.thing[i];things.thing = new Array();for ( var key in obj ) things.thing.push(obj[key]);
好吧,我认为应该这样做。看看,特拉维斯。
编辑
编辑代码以正确引用place
(以前id
)属性。
波斯汪
TA贡献1811条经验 获得超4个赞
如果您可以使用Javascript库,例如下划线或lodash,我建议您查看_.uniq
其库中的函数。来自lodash
:
_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])
基本上,你传入的数组在这里是一个对象文字,你传入要在原始数据数组中删除重复项的属性,如下所示:
var data = [{'name': 'Amir', 'surname': 'Rahnama'}, {'name': 'Amir', 'surname': 'Stevens'}];var non_duplidated_data = _.uniq(data, 'name');
收到一只叮咚
TA贡献1821条经验 获得超4个赞
我有完全相同的要求,根据单个字段上的重复项删除数组中的重复对象。我在这里找到了代码:Javascript:从对象数组中删除重复项
所以在我的例子中,我正在从数组中删除任何具有重复的licenseNum字符串值的对象。
var arrayWithDuplicates = [ {"type":"LICENSE", "licenseNum": "12345", state:"NV"}, {"type":"LICENSE", "licenseNum": "A7846", state:"CA"}, {"type":"LICENSE", "licenseNum": "12345", state:"OR"}, {"type":"LICENSE", "licenseNum": "10849", state:"CA"}, {"type":"LICENSE", "licenseNum": "B7037", state:"WA"}, {"type":"LICENSE", "licenseNum": "12345", state:"NM"}];function removeDuplicates(originalArray, prop) { var newArray = []; var lookupObject = {}; for(var i in originalArray) { lookupObject[originalArray[i][prop]] = originalArray[i]; } for(i in lookupObject) { newArray.push(lookupObject[i]); } return newArray; }var uniqueArray = removeDuplicates(arrayWithDuplicates, "licenseNum");console.log("uniqueArray is: " + JSON.stringify(uniqueArray));
结果:
uniqueArray是:
[{"type":"LICENSE","licenseNum":"10849","state":"CA"},{"type":"LICENSE","licenseNum":"12345","state":"NM"}, {"type":"LICENSE","licenseNum":"A7846","state":"CA"},{"type":"LICENSE","licenseNum":"B7037","state":"WA"}]
添加回答
举报
0/150
提交
取消