5

I need to push a JSON object to AngularJS and need to check before if the value for one of the objects exist. I need to overwrite the data.

$scope.setData = function(survey, choice) {

  keepAllData.push({
    'surveyId': survey.id,
    'choiceId': choice.id
  });
  console.log(keepAllData);
  toArray(keepAllData);
  alert(JSON.stringify(toArray(keepAllData)));

  $scope.keepAllDatas.push({
    'surveyId': survey.id,
    'choiceId': choice.id
  });
  var items = ($filter('filter')(keepAllDatas, {
    surveyId: survey.id
  }));

}

function toArray(obj) {
  var result = [];
  for (var prop in obj) {
    var value = obj[prop];
    console.log(prop);
    if (typeof value === 'object') {
      result.push(toArray(value));

      console.log(result);
    } else {
      result.push(value);
      console.log(result);
    }
  }
  return result;
}

If the survey id exists in keepalldata, I need to change the recent value with choiceid. Is it possible to do with AngularJS?

1

2 Answers 2

2

Try with this: Before pushing data you have to check if the survey id exists or not. If it exists you have to update choice with the corresponding survey id, otherwise you can push directly.

$scope.setData = function(survey, choice) {
  var item = $filter('filter')(keepAllData, {
    surveyId: survey.id
  });
  if (!item.length) {
    keepAllData.push({
      'surveyId': survey.id,
      'choiceId': choice.id
    });
  } else {
    item[0].choiceId = choice.id;
  }
  console.log(keepAllData);
}

Demo

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Balachandran, I have modified a few to remove the data if exist as well.
I did't get .do you want to update or remove if survey id is exist?
I just want to update the choice id alone for an existing survey id
Okay, I think the above code will work for you, Is not working ? or any issue?
Thanks Bala and the keepAllData is $scope.keepAllData
0
 $scope.keepAllDatas = [];

 $scope.setData = function(survey, choice) {

     if($scope.keepAllDatas.length == 0) {
         $scope.keepAllDatas.push({'surveyId':survey.id,'choiceId':choice.id});
     }
     else {
         var items = ($filter('filter')( $scope.keepAllDatas, {surveyId: survey.id }));
         for (var i = items.length - 1; i >= 0; i--) {
             // alert(items[i].surveyId);
             if(items[i].surveyId == survey.id) {
                 console.log($scope.keepAllDatas.indexOf(survey.id));
                 $scope.keepAllDatas.splice($scope.keepAllDatas.indexOf(survey.id),1);
                 console.log("Removed data")
             }
         }

         $scope.keepAllDatas.push({'surveyId':survey.id, 'choiceId':choice.id});
         console.log( $scope.keepAllDatas)
         // alert(items[0].surveyId);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.