将flattend数组结构化为树

时间:2016-06-29 05:08:41

标签: javascript angularjs recursion

我有一个结构为“id,name,parent_name”的对象列表,我需要得到一个带有名称的树。

例如:

var employees = [];

var kirk = new Person(uuid(), 'Kirk', null);
employees.push(kirk);

var mark = new Person(uuid(), 'Mark', kirk);
employees.push(mark);

var tom1 = new Person(uuid(), 'Tom', mark);
employees.push(tom1);

var nick = new Person(uuid(), 'Nick', tom1);
employees.push(nick);

var ben = new Person(uuid(), 'Ben', tom1);
employees.push(ben);

var david = new Person(uuid(), 'David', ben);
employees.push(david);

var stacey = new Person(uuid(), 'Stacey', nick);
employees.push(stacey);

var corey = new Person(uuid(), 'Corey', nick);
employees.push(corey);

var tom2 = new Person(uuid(), 'Tom', stacey);
employees.push(tom2);

var julie = new Person(uuid(), 'Julie', stacey);
employees.push(julie);

员工是我的扁平化列表,我需要结果 Kirk{Mark{Tom{Ben{David},Nick{Corey,Stacey{Julie,Tom}}}}}

1 个答案:

答案 0 :(得分:0)

请确认这是否是您想要的:

function uuid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

var Person = function(id, name, parent_name) {
	this.id = id;
  this.name = name,
  this.parent_name = parent_name;
  this.sub = [];
  
  this.addSubPerson = function(person) {
  	this.sub.unshift(person); //Chnaged from 'push' to 'unshift'
    return person;
  };
  
  this.subPersons = function() {
    if(this.sub.length) {	
    	var result = [];
        for(var i in  this.sub) {
            result.push(this.sub[i].subPersons());
        }
  		return this.name + '{'+ result.join(',') + '}';
    }else {
    	return this.name;
    }
  };
};

var employees = [];

var kirk = new Person(uuid(), 'Kirk', null); 
employees.push(kirk);

var mark = new Person(uuid(), 'Mark', kirk); 
employees.push(mark);

var tom1 = new Person(uuid(), 'Tom', mark); 
employees.push(tom1);

var nick = new Person(uuid(), 'Nick', tom1); 
employees.push(nick);

var ben = new Person(uuid(), 'Ben', tom1); 
employees.push(ben);

var david = new Person(uuid(), 'David', ben); 
employees.push(david);

var stacey = new Person(uuid(), 'Stacey', nick); 
employees.push(stacey);

var corey = new Person(uuid(), 'Corey', nick); 
employees.push(corey);

var tom2 = new Person(uuid(), 'Tom', stacey); 
employees.push(tom2);

var julie = new Person(uuid(), 'Julie', stacey); 
employees.push(julie);

for(var i in employees) {
	var employee  = employees[i];
  if(employee.parent_name != null) {
  	employee.parent_name.addSubPerson(employee);	
  }
}

console.log(kirk.subPersons());