我将这样的数据存储在 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/