收到一只叮咚
我有完全相同的要求,根据单个字段上的重复项删除数组中的重复对象。我在这里找到了代码: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"}]