如果不存在angularjs,则将对象推送到空数组

时间:2018-05-07 01:49:33

标签: javascript arrays angularjs json

我创建的数组是空的。我想推独特的对象。我想用于循环。但首先数组长度为零。所以不适用于循环。我该怎么办?

$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});                                             
    }
}   

1 个答案:

答案 0 :(得分:1)

使用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);