作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我创建的数组是空的。我想推送独特的对象。我想使用 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/
我是一名优秀的程序员,十分优秀!