2017-04-20 80 views
0

无论何时用户单击前端的星号,我都会在数组中插入一个对象并使用两个键question_idrating。如果用户更改任何恒星的评级,然后更新现有密钥的值(如果存在),则会查找我要查找的内容,否则将条目推入阵列。下面在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'srating,阵列应该仅5个元素。

谢谢

+1

那么问题是什么? – gforce301

+0

我的问题是我如何只保留一个与1特定的question_id相对应的评级,现在发生的是更新当前值以及插入新值。我不希望它插入新值,只要更新对应于该特定键的值(如果存在),或者将其插入到数组中。 –

回答

1

它与你的if/else在for循环中有关。要检查,如果在for循环迭代当前元素是同一个问题:

if ($scope.yellowPages[i]["question_id"] == question_id) { 

如果不是,你是推项目到数组:

$scope.yellowPages.push({rating: rating, question_id: question_id}); 

发生这种情况的每次迭代循环。例如,如果数组中有3个项目,并且匹配的问题ID是第三个项目,则会将一个新对象($ scope.yellowPages.push({rating:rating,question_id:question_id});)插入到数组两次到达第三个索引中的匹配对象并更新其评分。

+0

我认为你是对的肯,但我该如何解决它,任何建议? –

+1

@VibhooMishra在foreach循环中,您可以使用设置为false的布尔值来代替foreach循环中的else语句。然后在foreach循环中,如果找到问题,则将布尔值设置为true。然后在foreach循环之后,检查是否找到问题,如果不是,则将问题推送到您的数组中。 以下是一些更新代码的示例,https://pastebin.com/1vh9YwDD 编辑:用pastebin更新 – Ken

0

为什么使用数组?而是使用如下所示的对象:

$scope.yellowPages = { 
    "question_id1": "rating1", 
    "question_id2": "rating2" 
} 

使用此功能,您可以轻松访问您的问题而无需循环。

0

我这样做只是为了更新现有的值,因为我只需要5个值在数组中存在,所以我只在插入5个初始值后才检查。但我认为这不是最理想的方式来实现它,但这解决了我的问题,任何其他帮助表示赞赏

if ($scope.yellowPages.length >= 5) { 
    for (var i = 0 ; i < $scope.yellowPages.length; i++) { 
     if ($scope.yellowPages[i]["question_id"] == question_id) { 
     $scope.yellowPages[i]["rating"] = rating; 
     } 
    } 
    } 
    else{ 
    $scope.yellowPages.push({rating: rating, question_id: question_id}); 
    }