我想创建一个函数,它将生成一个像结构这样的树,以便每个项目包含对它的父项目的引用。Javascript递归函数参考这个
我有一个函数可以在创建孩子时调用自己,但是对它有困难的时候,似乎一旦从它自己内部调用它,this
仍然指向顶级项目而不是当前项目。
记录控制项目是什么我可以看到,父母始终指的是链中的第一项(或缺席)比第一级更深。它创建树,但除了第一个项目之外,对父项的引用会丢失。
var Item = function (item, parent) {
console.log('item is :' + item.name);
this.parent = parent;
console.log('parent is: ' + parent);
var fields = _.union(_.keys(item), _.keys(this.parent));
_.each(_.without(fields, ['parent','children']), function (prop) {
this[prop] = angular.isDefined(item[prop]) ? item[prop] : this.parent[prop];
}, this);
this.children = [];
if (item.children) {
this.children = _.map(item.children, function (child) {
console.log('this is : ' + this);
return new Item(child, this)
}, this);
}
};
var tree = new Item(root, {});
有一点麻烦小提琴去,但这里是一些样本数据:
var root = JSON.parse('{"id":"1","name":"root item","root":"1","lft":"1","rgt":"22","level":"1","type":
"category","parent_id":"1","deadline":null,
"children":[
{"id":"2","name":"item 1","root":"1","lft":"14","rgt":"15","level":"2","type":"category","parent_id":"1"},
{"id":"6","name":"item 2","root":"1","lft":"16","rgt":"19","level":"2","type":"category","parent_id":"1"},
{"id":"10","name":"item 3","root":"1","lft":"20","rgt":"21","level":"2","type":"item","parent_id":"1"}]}');
只是一个错字,我一直在试验,并忘记修改之前发布。修正它在这里,问题仍然是一样的。 – JPR
你可以用一些虚拟数据为此创建小提琴吗? –
当然,可能需要几分钟才能把它放在一起。谢谢。 – JPR