【树结构】构造树结构(优化版)

function Container()
{
this.keySet = [];
this.entrySet = {};

this.put = function(key, value)
{
this.keySet.push(key);
this.entrySet[key] = value;
return this;
}

this.get = function(key)
{
return this.entrySet[key];
}

this.keys = function()
{
return this.keySet;
}

this.size = function()
{
return keySet.length;
}
}

function Region(id, name, pId, level, type)
{
this.id = id;
this.name = name;
this.pId = pId;
this.level = level;
this.type = type;
this.parent = false;
this.children = false;
this.status = false;
}

Region.prototype.getId = function()
{
return this.id;
}

Region.prototype.getName = function()
{
return this.name;
}

Region.prototype.getPId = function()
{
return this.pId;
}
Region.prototype.getStatus = function()
{
return this.status;
}
Region.prototype.setStatus = function(status)
{
this.status = status;
}

Region.prototype.setParent = function(parent)
{
this.parent = parent;
}

Region.prototype.getParent = function()
{
return this.parent;
}

Region.prototype.addChildren = function(child)
{
this.children = this.children || [];
this.children.push(child);
}

Region.prototype.getChildren = function()
{
return this.children;
}

Region.prototype.childOf = function(child)
{
if(!this.children || !child || !(child instanceof Region))
{
return false;
}

for(var i in children)
{
if(children[i] == child)
{
return true;
}
}

return false;
}

var data=othis.option.data; 
var container = new Container();
var oldData = eval($(oCheck).val());
for(var i = 0; i < data.length; i++)
{
var item = data[i];
var region = new Region(item.id, item.name, item.pId, item.level, item.type);
container.put(item.id, region);
}

var keys = container.keys();

for(var i in keys)
{
var region = container.get(keys[i]);
var pId = region.getPId();

if(region.level!=1)//pId != 0)
{
parentRegion = container.get(pId);
region.setParent(parentRegion);
parentRegion.addChildren(region);
}
}

console.log(container);

原文地址:https://www.cnblogs.com/yyumeng/p/8598927.html