使用lodash将数组分组为树"children"结构

Use lodash to group array into tree "children" structure

使用lodash,我需要转换以下数组:

[{
    text: 'apple',
    type: 'fruit'
}, {
    text: 'pear',
    type: 'fruit',
}, {
    text: 'potato',
    type: 'vegetable'
}, {
    text: 'water',
    type: 'beverage'
}]

转换成如下格式:

[{
    text: 'fruit',
    children: [{
        text: 'apple',
        type: 'fruit'
    }, {
        text: 'pear',
        type: 'fruit'
    }]
}, {
    text: 'vegetable',
    children: [{
        text: 'potato',
        type: 'vegetable'
    }]
}, {
    text: 'beverage',
    children: [{
        text: 'water',
        type: 'beverage'
    }]
}]

我曾尝试链接 lodash 方法,如 groupBytransform,但很难获得我需要的结果格式。

这是我前进方向的框架:

_(arr).groupBy('type').transform(function(result, obj, type) {
    return result.push({
        name: type,
        children: obj
    });
}).value();

我 运行 遇到的问题是 groupBy 将我的数组转换为对象,因此我不能再简单地 push 到数组上。由于对 lodash 比较了解(大约 4 或 5 个月的经验),我想看看其他人是否已经解决了这样的需求。

使用 _.reduce() 而不是转换,因为它可以让您声明最终产品格式:

var arr = [{
  text: 'apple',
  type: 'fruit'
}, {
  text: 'pear',
  type: 'fruit',
}, {
  text: 'potato',
  type: 'vegetable'
}, {
  text: 'water',
  type: 'beverage'
}];

var results = _(arr)
  .groupBy('type')
  .reduce(function(array, children, key) {
    array.push({
      text: key,
      children: children
    });

    return array;
  }, []);

console.log(results);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>