如何在AngularJS中将JSON对象推入数组

5

我需要将一个JSON对象推送给AngularJS,并在此之前检查其中一个对象的值是否存在。我需要覆盖数据。

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

如果调查 ID 在 keepalldata 中存在,我需要使用 choiceid 更改最近的值。是否可以使用 AngularJS 完成?

请查看此链接:https://dev59.com/UWYq5IYBdhLWcg3wbgHk[javascript-object-pushed-into-an-array] - Jagan C
2个回答

2

请尝试以下方法:在推送数据之前,您需要检查调查ID是否存在。如果存在,则必须使用相应的调查ID更新选择,否则可以直接推送。

$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


谢谢Balachandran,我已经修改了一些内容以删除数据(如果存在的话)。 - user3428736
我不明白。如果调查ID已存在,您是要更新还是删除? - Balachandran
我只想更新现有调查ID的选择ID。 - user3428736
好的,我认为上面的代码对你来说应该是可行的,有没有出现问题或者任何疑问? - Balachandran
1
感谢Bala,keepAllData是$scope.keepAllData - user3428736

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接