按ID比较Javascript对象以在/JS中创建唯一列表
我调用了GithubAPI,它为我提供了一个包含提交的对象数组。我想循环一下,得到一个唯一的提交人列表,并以以下格式构建它:按ID比较Javascript对象以在/JS中创建唯一列表,javascript,angularjs,Javascript,Angularjs,我调用了GithubAPI,它为我提供了一个包含提交的对象数组。我想循环一下,得到一个唯一的提交人列表,并以以下格式构建它: {"id":temp,"label":temp,"type": "number","p": {} } 所以我可以把它画出来 我写了以下内容: $scope.git = response.data; $scope.o=[]; angular.forEach($scope.git,function(value){ var temp = value
{"id":temp,"label":temp,"type": "number","p": {} }
所以我可以把它画出来
我写了以下内容:
$scope.git = response.data;
$scope.o=[];
angular.forEach($scope.git,function(value){
var temp = value.commit.author.name;
if($scope.o.length==0){
$scope.o.push({"id":temp,"label":temp,"type": "number",
"p": {}
})
}
else{
angular.forEach($scope.o,function(ob){
if(ob.id==temp){
continue;
}
else{
$scope.o.push({"id":temp,"label":temp,"type": "number",
"p": {}
})
}
});
}
})
这是可行的,但效率极低。正确的方法是什么 您可以使用对象检查是否已将作者插入列表。比如:
$scope.o = [];
var authors = {};
angular.forEach($scope.git, function(value){
var temp = value.commit.author.name;
if (authors[temp] === undefined) {
$scope.o.push({"id":temp,"label":temp,"type": "number", "p": {} });
authors[temp] = true;
}
});
您也可以使用下划线或lodash之类的库。这里有用的方法之一是uq.uniqBy。这里是相同的文档