假如是在vue中使用该方法:
<script>
export default {
created(){
let fruitSamples = [
{ id: 1, type: 'apples', samples: [{ id: 1, name: 1 }] },
{ id: 2, type: 'bananas', samples: [{ id: 2, name: 2 }] },
{ id: 3, type: 'pears', samples: [{ id: 3, name: 3 }] },
{ id: 1, type: 'apples', samples: [{ id: 11, name: 11 }] },
]
this.mergeArrObj(fruitSamples,'type');
},
methods:{
// fruitSamples需要合并的数组对象,type需要依据哪个属性合并
mergeArrObj(fruitSamples,type){
function customizer(objValue, srcValue) {
if (_.isArray(objValue)) {
return objValue.concat(srcValue)
}
}
// 传需要处理的参数过去
let test = _(fruitSamples)
.flatten()
.groupBy(type)
.map(
_.spread((...values) => {
console.log("value是多少")
console.log(...values);
return _.mergeWith(...values, customizer)
}),
)
.value()
console.log("test为多少")
console.log(test)
// ->结果如下:
[
{ id: 1, type: 'apples', samples: [1, 2, 3, 5, 2, 9, 11, 2, 33] },
{ id: 2, type: 'bananas', samples: [1, 2, 7, 1, 7, 7, 17, 2, 67] },
{ id: 3, type: 'pears', samples: [1, 2, 3, 12, 21, 32, 91, 22, 34] }
]
}
}
}
</script>