我有以下代码,当用户在每个产品描述页面上点击 compre 时,我使用本地存储来存储产品变体 ID 数组。:
“Prdvar”包含产品变体 ID(例如:10,13 等)
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));
$scope.dataVarID = JSON.parse(localStorage.getItem('session'));
alert($scope.dataVarID); //Duplicate values present
$scope.CompareProduct = function() {
a = JSON.parse(localStorage.getItem('session'));
a.push("{ ProductVarient :"+Prdvar+"}");
alert(a);
localStorage.setItem('session', JSON.stringify(a));
};
我的问题是如何删除 $scope.dataVarID 中存在的重复项目。
,{ ProductVarient :5},{ ProductVarient :5},{ ProductVarient :5},{ ProductVarient :33}
//我不知道在 首先,添加然后 12,13,12,12
我只需要 ,{ ProductVarient :5},{ ProductVarient :33}
最佳答案
您可以使用 map 并过滤掉重复项
//$scope.dataVarID = JSON.parse(localStorage.getItem('session'));
function getUniqueArrayObject(array) {
var result = array.map(function(a) {
return a.ProductVarient;
});
var unique = [];
for (var x = 0; x < result.length; x++) {
if (unique.indexOf(result[x]) == -1) unique.push(result[x]);
}
return (unique.map(function(a) {
return {
ProductVarient: a
};
}))
}
var newArray = getUniqueArrayObject([{ ProductVarient :5},{ ProductVarient :5},{ ProductVarient :5},{ ProductVarient :33}])
console.log(newArray)
// $scope.newArray=getUniqueArrayObject($scope.dataVarID);
关于javascript - 如何删除范围变量中存在的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45980014/