我有完全相同的要求,根據(jù)單個字段上的重復項刪除數(shù)組中的重復對象。我在這里找到了代碼:Javascript:從對象數(shù)組中刪除重復項
所以在我的例子中,我正在從數(shù)組中刪除任何具有重復的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));
結(jié)果:
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"}]