【问题标题】:Push object to empty array if not exist angularjs如果不存在angularjs,则将对象推送到空数组
【发布时间】:2018-05-07 01:49:32
【问题描述】:

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

$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.include() 函数作为检查?
  • 感谢回答我使用了 Array.include 函数。当循环工作时总是返回 false。

标签: javascript arrays angularjs json


【解决方案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);

【讨论】:

  • 感谢您的回答,但我不应该减少 $scope.result。因为我必须使用另一个循环
  • @Hermes 更新了答案。它不会改变您的result。立即检查。
  • 这行得通,但不能完美地工作。有些值是重复的。如何使用多重过滤器?例如我想使用 categoryPercent 和 categoryInt
  • 你的预期输出是什么?
  • 你的答案是正确的,但是。 $scope.result 不仅仅是属性。我写了一些属性。当我使用你的代码时,一些值被推送到 $scope.arr。所以我想我必须使用多重过滤器,例如 arr = Object.values(result.reduce((acc, cur) => Object.assign(acc, { [cur.categoryPercent, cur.categoryInt ]: cur }), { }));
猜你喜欢
  • 1970-01-01
  • 2018-08-09
  • 1970-01-01
  • 2017-05-10
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多