我创建的数组为空。我要推送唯一的对象。我想使用循环。但首先,数组长度为零。因此,不适用于循环。我能怎么做?

$scope.arr=[];
$scope.result=[
   {category: "Home", categoryInt: 1, categoryPercent:50},
   {category: "Office", categoryInt: 1, categoryPercent:25},
   {category: "Office", categoryInt: 1, categoryPercent:25},
   {category: "Office", categoryInt: 1, categoryPercent:25}
[
for(var z=0; z<$scope.arr.length; z++){
    if ($scope.arr[z].percent === $scope.result[a].categoryPercent) {
        return;
    } else {
        $scope.arr.push({category: $scope.result[a].category, percent: $scope.result[a].categoryPercent, categoryInt: $scope.result[a].categoryInt});
    }
}

最佳答案

使用Array.reduce()具有唯一对象的对象数组。下面是工作代码:



let arr = [];
var result = [{category:"Home",categoryInt:1,categoryPercent:50},{category:"Office",categoryInt:1,categoryPercent:25},{category:"Office",categoryInt:1,categoryPercent:25},{category:"Office",categoryInt:1,categoryPercent:25}];

arr = Object.values(result.reduce((acc, cur) => Object.assign(acc, {
  [cur.categoryPercent]: cur
}), {}));

console.log(arr);

10-06 03:57