angularjs - 如何将 JSON 对象推送到 AngularJS 中的数组

标签 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;
}
如果keepalldata 中存在调查ID,我需要使用choiceid 更改最近的值。是否可以使用 AngularJS?

最佳答案

试试这个:在推送数据之前,您必须检查调查 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

关于angularjs - 如何将 JSON 对象推送到 AngularJS 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38700877/

相关文章:

javascript - 如何在 AngularJS 部分文件中使用 php (wordpress) 函数?

angularjs - 如何为不同的项目版本和管理 angularjs 组件

javascript - Angular 在服务内部创建新范围

javascript - 尝试在我的网络应用程序中测试 google oauth 时出现 popup_closed_by_user 错误

javascript - 使用 ng-repeat 使用实时数据动态更新 bootstrap angularjs 表

javascript - Kendo Grid 工具栏项目未触发单击功能 :

javascript - 我对 Angular 状态 promise 解决有什么误解?

javascript - 咕噜声 : Dist folder not created after grunt command

angularjs - 通过 angularjs 从 REST api 建模关系数据