Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push a JSON object to an array in AngularJS

Tags:

angularjs

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?

like image 867
user3428736 Avatar asked Oct 29 '22 23:10

user3428736


1 Answers

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

like image 63
Balachandran Avatar answered Nov 15 '22 07:11

Balachandran