无论何时用户单击前端的星号,我都会在数组中插入一个对象并使用两个键question_id
和rating
。如果用户更改任何恒星的评级,然后更新现有密钥的值(如果存在),则会查找我要查找的内容,否则将条目推入阵列。下面在javascript/angularjs中更新哈希中的键的现有值
$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个元素。
谢谢
那么问题是什么? – gforce301
我的问题是我如何只保留一个与1特定的question_id相对应的评级,现在发生的是更新当前值以及插入新值。我不希望它插入新值,只要更新对应于该特定键的值(如果存在),或者将其插入到数组中。 –