Javascript 使用lodash将数组分组到树中;“儿童”;结构
使用lodash,我需要转换以下数组:Javascript 使用lodash将数组分组到树中;“儿童”;结构,javascript,arrays,group-by,lodash,Javascript,Arrays,Group By,Lodash,使用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: '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方法,如groupBy
和transform
,但我很难获得所需的结果格式
下面是我前进方向的大致情况:
_(arr).groupBy('type').transform(function(result, obj, type) {
return result.push({
name: type,
children: obj
});
}).value();
我遇到的问题是groupBy
将我的数组变成了一个对象,因此我不能再简单地将推到数组上。由于对lodash比较了解(大约4或5个月的经验),我想看看其他人是否已经解决了这样的要求。使用而不是转换,因为它可以让您陈述最终产品格式:
var-arr=[{
文字:“苹果”,
类型:“水果”
}, {
文字:'梨',
类型:'水果',
}, {
文字:“土豆”,
类型:“蔬菜”
}, {
文字:“水”,
类型:“饮料”
}];
var结果=U8;(arr)
.groupBy('type'))
.reduce(函数(数组、子项、键){
array.push({
文本:键,
儿童:儿童
});
返回数组;
}, []);
控制台日志(结果)代码>
我会注意到,使用以下代码段是可行的,但我愿意接受更干净的解决方案:(arr.pull('type').uniq().transform(function(result,type){return result.push({text:type,children:).where(arr,{type:type});}).value()代码>。我唯一关心的是这个代码片段失去了对原始对象的引用,因此如果有额外的信息,比如id
或state
对象,我会在转换中丢失这些数据。非常感谢!我相信你发布的正是我想要做的,它的效果和我上面的片段一样好,但我认为你的更好用。