【问题标题】:How to push a JSON object to an array in AngularJS如何将 JSON 对象推送到 AngularJS 中的数组
【发布时间】:2016-12-06 15:41:21
【问题描述】:

我需要将一个 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;
}

如果keepalldata中存在调查id,我需要用choiceid更改最近的值。可以用AngularJS吗?

【问题讨论】:

标签: angularjs


【解决方案1】:

试试这个:在推送数据之前,您必须检查调查 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,我已经修改了一些以删除数据(如果存在)。
  • 我没有收到。如果调查 ID 存在,您要更新还是删除?
  • 我只想单独更新现有调查 ID 的选择 ID
  • 好的,我想上面的代码对你有用,是不是不行?还是有什么问题?
  • 感谢 Bala,keepAllData 是 $scope.keepAllData
【解决方案2】:
 $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);
    }
}

【讨论】:

    猜你喜欢
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 2018-11-10
    相关资源
    最近更新 更多