javascript - 比较两个数组并按原样获取数据

标签 javascript angularjs

我将这样的数据存储在 scope 变量中:

$scope.myData = 
    {
      "firstName": "rocky",
      "lastName": "P",
      "place": "Koraput",
      "education": [
        {
          "id": "764006"
        },
        {
          "id": "764001"
        }
      ],
      "email": "rockyp123@gmail.com",
      "id": "46ads75asda7s6d57ad"
    }

案例:假设我正在更新此数据。我向其中添加了教育内容,然后单击取消。如何在点击取消时删除当前添加的教育并在点击编辑用户时检索上述仅两个教育的数据?

最佳答案

您应该保留两个单独的对象,一个是原始的、未更改的对象,另一个用于编辑。一旦用户单击“保存”,您才可以用第二个对象覆盖第一个对象。单击取消后,您只需将可编辑对象的值恢复为原始数据的克隆即可。

您首先将第一个对象克隆到新的第二个对象中:

// Your original data (unchanged)
$scope.myData = { /* ... */ };

// Your object for editing purposes
$scope.myDataClone = clone($scope.myData);

$scope.cancel = function() {
  // reset the 'editable' clone to the unchanged value of myData
  $scope.myDataClone = clone($scope.myData);
}

$scope.save = function() {
  // Once the user accepts their changes, you can simply
  // set the value of myData to a clone of the edited data.
  // This will ensure you are not just creating a new pointer
  // from myData to myDataClone, which would cause myData
  // to change if you make subsequent requests to myDataClone.
  $scope.myData = clone($scope.myDataClone);
}

// A clone function which takes an object and returns an exact
// replica as a new object with a unique memory reference
function clone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

关于javascript - 比较两个数组并按原样获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43650198/

相关文章:

javascript - 如何通过 Bootstrap 使用 redux 表单宽度 "Field"

AngularJS 未定义、null 和 0

javascript - 无法使用 Wcf 服务在 Angular JS 中根据 ID 检索单个记录

angularjs - 如何在 AngularJS 上验证对 OrientDB 函数的 HTTP 请求?

javascript - 如何恢复以前的 Angular Controller 状态

javascript - 如何处理 Node 中的递归回调?

javascript - 如何在javascript中使用pdf的字节数组在浏览器中显示pdf?

javascript - 在 for 循环中添加 jQuery Click 函数

AngularJS 路由器 - 第二次不起作用

angularjs - 脚本标签中的 ng-src