【发布时间】:2017-04-20 19:08:31
【问题描述】:
每当用户单击前端的星号时,我都会在具有两个键 question_id 和 rating 的数组中插入一个对象。如果用户更改任何星的评级然后更新现有键的值(如果存在),我正在寻找什么,否则将条目推送到数组。
下面的代码示例
$scope.yellowPages = [] // is defined
if ($scope.yellowPages.length > 1) {
for (var i = 0 ; i < $scope.yellowPages.length; i++) {
if ($scope.yellowPages[i]["question_id"] == question_id) {
$scope.yellowPages[i]["rating"] = rating; // here updating the existing value of key, but what is happening it's updates and as well as creates a new entry with the updated value.
}
else{
$scope.yellowPages.push({rating: rating, question_id: question_id});
} // if not present
}
}
else{
$scope.yellowPages.push({rating: rating, question_id: question_id}); // for 1st time
}
}
我的最终目标是拥有一个独特的question_id's 和rating,数组应该只有5 个元素。
谢谢
【问题讨论】:
-
那么问题是什么?
-
我的问题是我如何只保留一个与 1 个特定 question_id 相对应的评级,现在发生的是它正在更新当前值以及插入新值。我不希望它插入新值,只需更新与该特定键对应的值(如果存在),否则将其插入数组中。
标签: javascript angularjs arrays rating-system