简体   繁体   中英

Update existing value of a key in a hash in javascript/angularjs

I'm inserting an object in an array with two keys question_id and rating whenever user clicks a star on front-end. What I'm looking for if user changes the rating of any of the star then update the value of the existing key (if present) otherwise push the entry to the array.

Code sample below

$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
  } 
}

My ultimate goal is to have a unique question_id's and there rating , array should only 5 elements.

Thanks

It has to do with your if/else in the for loop. you are checking if the current element in the forloop iteration is the same question:

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

If it is not, you are pushing the item into the array:

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

This happens for every iteration of the loop. So for example if you have 3 items in the array, and the matching question id is the third item, you will push a new object ($scope.yellowPages.push({rating: rating, question_id: question_id});) into the array twice before reaching the matching object in the third index and updating its rating.

Why are you using an array? Instead use an object that looks like this:

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

with this you can easily access your questions without looping.

I'm doing this way just to update the existing value, since I only need 5 values to be present in array, so I'm checking only after 5 initial values are inserted. However I think this is not the most optimal way to achieve it, but this solved my problem.

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});
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM