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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3428736
  • 864
  • 2
  • 13
  • 33
  • check this http://stackoverflow.com/questions/14489860/[javascript-object-pushed-into-an-array] – Jagan C Aug 01 '16 at 14:07

2 Answers2

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Balachandran
  • 9,567
  • 1
  • 16
  • 26
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);
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3428736
  • 864
  • 2
  • 13
  • 33