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

use*_*736 5 angularjs

我需要将一个 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Bal*_*ran 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);
}
Run Code Online (Sandbox Code Playgroud)

演示