以角度深度复制对象? [英] Deep copying objects in angular?

查看:26
本文介绍了以角度深度复制对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当您需要创建一个具有嵌入对象数组的简单对象时,是否可以避免复制对对象的引用.情况如下:我有一个接受 JSON 并应用一些逻辑然后存储的服务器DB 中的对象.可以说我的表格是用于在 DB 中保存团队.服务器接受团队为 json.团队有一个 TeamMember 对象数组,我的表单有一个简单的字段来输入团队成员信息并将其添加到团队 teamMembers 数组中.现在问题来了,当我将一个团队成员添加到数组列表并想在我输入字段时添加另一个团队成员时,添加的成员也被更改了!.我知道原因

I wonder if there is away to avoid copying references to objects when you need to create a simple object which has an array of embedded objects.The situation is as follow: I have server which accepts a JSON and applies some logic then stores the object in DB. lets say my form is for saving teams in DB. The server accepts team as json. the team has an array of TeamMember objects, my form has a simple field to enter team member info and add it to team teamMembers array. Now here is the problem, when I add a team member to array list and want to add another team member when I type into the field the added member is changed also !. I know the reason

$scope.addTeamMember=function(teamMember){
   $scope.team.teamMembers.push(teamMember);
}

这是因为我将相同的引用放入 teamMembers 数组中,所以我多次添加了相同的对象.为了避免这种情况,我应该创建一个新的团队成员对象,复制所有 teamMember 属性并将其添加到数组中.

and it is because I put same reference into the teamMembers array so I have same object added several times. to avoid this I should create a new team member object, copy all teamMember properties and and add it the array.

 $scope.addTeamMember=function(teamMember){
       var newTeamMember; /*<--- copy teamMember */
       $scope.team.teamMembers.push(newTeamMember); /*and add newTeamMember*/
    }

推荐答案

你的问题说你想避免深度复制",但我不确定这是否准确.听起来您只想使用 angular.copy,因为您需要创建团队成员的副本并将其添加到数组中:

Your question says you want to "avoid deep copy", but I'm not sure that's accurate. It sounds like you just want to use angular.copy, because you need to create a copy of the team member and add that to the array:

$scope.addTeamMember = function(teamMember) {
   var newTeamMember = angular.copy(teamMember);
   $scope.team.teamMembers.push(newTeamMember);
};

这篇关于以角度深度复制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆