这个方法当时在做项目时写的,应用在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;
}