Js深度克隆对象(对象的属性含有对象数组)

这个方法当时在做项目时写的,应用在easyui的Tree组件中。

后台Java对象结构:List<TreeObj>

public class TreeObj {
	private String id;
	private String text;
	private List<TreeObj> children = new ArrayList<TreeObj>();
	private String state ;
	private String iconCls;
	private Object attributes ;
	private boolean checked = false;
}


js代码:

//克隆树数据对象
function clone(targetList,childrenList,cloneList){
	for(key in targetList){
		//----取值  start--------------------------------------------------------
		var obj = targetList[key];
		var newObj = {};
		newObj.id = obj.id;
		newObj.text = obj.text;
		newObj.state =obj.state;
		newObj.checked = obj.checked;
		var attr = {};attr.parentNode ="";attr.nodeHeirdomRelation = "";
		if(obj.attributes){
			if(obj.attributes.parentNode){
				attr.parentNode = obj.attributes.parentNode ;
			}
			if(obj.attributes.nodeHeirdomRelation){
				attr.nodeHeirdomRelation = obj.attributes.nodeHeirdomRelation ;
			}
		}
		newObj.attributes = attr;
		//---取值  end---------------------------------------------------------
		if(childrenList){childrenList.push(newObj);}//保存子节点成员
		
		if(obj.children != null && obj.children.length>0){	
			var newList = new Array();//保存当前节点的子节点		
			clone(obj.children,newList,cloneList);			
			newObj.children = newList;			
		}
		if(/^rl_.*$/.test(obj.id.toLowerCase())){//从根部开始保存
			cloneList.push(newObj);//保存根节点
		}
	}
}


调用;

clone(源数组,null,克隆后);

 

在网上找到这个办法,但好像不能克隆带对象属性的数组,目前我还没对他进行过测试。


Object.prototype.Clone = function(){
    var objClone;
    if (this.constructor == Object){
        objClone = new this.constructor(); 
    }else{
        objClone = new this.constructor(this.valueOf()); 
    }
    for(var key in this){
        if ( objClone[key] != this[key] ){ 
            if ( typeof(this[key]) == 'object' ){ 
                objClone[key] = this[key].Clone();
            }else{
                objClone[key] = this[key];
            }
        }
    }
    objClone.toString = this.toString;
    objClone.valueOf = this.valueOf;
    return objClone; 
} 


 

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值