【问题标题】:Underscore/Lodash - Object from parent/children下划线/Lodash - 来自父/子的对象
【发布时间】:2015-07-17 06:47:13
【问题描述】:

我正在尝试从我从数据库 (Mongo) 获取的集合中创建一个格式化集合。

这是输入的格式:

[{_id:1,name:'1'},
 {_id:2,name:'2},
 {_id:3,name:'1-1',parent:1},
 ...
 {_id:50,name:'1-1-3',parent:3}]

如您所见,“最深的祖先”是 _id 1 和 2。子节点的第一个节点包含 _id 3,它有一个子节点 _id 50。

我正在努力使用 Lodash 创建这种集合:

[{
    _id:1,name:'1',children:[
        {_id:3,name:'1-1',children:[
            ...,
            {_id:50,name:'1-1-3',children:[]}
        ]},
        ...
    ]
},{
    _id:1,name:'1',children:[...]
}]

这是我尝试过的:

var result=_.chain(input)
    .groupBy('parent')
    .pairs()
    .map(function(currentItem){
        return _.object(_.zip(['parent','children'],currentItem))
    })
    .value();

但它不能以递归方式工作......

有人可以帮助我吗?

谢谢。

【问题讨论】:

    标签: recursion underscore.js lodash


    【解决方案1】:

    您可以遍历集合以获得所需的结构:

    // create and indexed object with the _id field as key - improve performance
    var indexed = _.indexBy(data, '_id');
    
    // iterate to create the structure
    _.each( data, function(datum){
       datum.children = [];
       if( _.has(datum,'parent')){
          indexed[datum.parent].children.push(datum);
        }
    })
    

    此解决方案确实假设在每个孩子之前处理父级,即子级数组是在推入之前创建的。如果需要,有多种解决方法,但上面的代码显示了创建嵌套结构的方法。

    【讨论】:

    • 感谢有关 indexBy 的提示。我添加了以下代码以仅保留最深的父母并拥有我想要的结构:_.map(data,function(d){if(!('parent' in d)){finalArray.push(d);};});
    猜你喜欢
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    相关资源
    最近更新 更多