gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:22:22 26 4
gpt4 key购买 nike

我创建的数组是空的。我想推送独特的对象。我想使用 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.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);

关于javascript - 如果不存在则将对象推送到空数组angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50206131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com