2017-04-20 81 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}); 
    }