我得到了这个数组,并且想要在代码,名称,文档和值的值都相等并且将月份和小时连接在一起时连接对象。我尝试使用lodash失败。
有没有办法使用lodash做到这一点?我尝试将groupBy与unionBy一起使用没有成功..结果是混乱的数组。谢谢。
const arrayOfObject = [
{
code: '6666',
name: 'Foo Bar',
doc: '60170150166',
value: '158.56',
month: '082011',
hours: '20'
},
{
code: '6666',
name: 'Foo Bar',
doc: '60170150166',
value: '158.56',
month: '092011',
hours: '20'
},
{
code: '6666',
name: 'Foo Bar',
doc: '60170150166',
value: '158.56',
month: '102011',
hours: '10'
},
{
code: '6666',
name: 'Foo Bar',
doc: '60170150166',
value: '169.81',
month: '042012',
hours: '10'
},
{
code: '6666',
name: 'Foo Bar',
doc: '60170150166',
value: '169.81',
month: '052012',
hours: '10'
}
];
这是预期的结果:
const expectedArray = [
{
code: '6666',
name: 'Foo Bar',
doc: '60170150166',
value: '158.56',
month: '082011, 092011, 102011',
hours: '20, 20, 10'
},
{
code: '6666',
name: 'Foo Bar',
doc: '60170150166',
value: '169.81',
month: '042012, 052012',
hours: '10, 10'
}
];
使用键对键进行分组_.groupBy()
,然后使用_.map()
合并每个组的项目_.mergeWith()
:
const combine = _.flow([
arr => _.groupBy(arr, o => [o.code, o.name, o.document, o.value].join('-')),
groups => _.map(groups, g => _.mergeWith(...g, (o, s, k) => {
if(k === 'month' || k === 'hours') return `${o}, ${s}`;
}))
]);
const arrayOfObject = [{"code":"6666","name":"Foo Bar","doc":"60170150166","value":"158.56","month":"082011","hours":"20"},{"code":"6666","name":"Foo Bar","doc":"60170150166","value":"158.56","month":"092011","hours":"20"},{"code":"6666","name":"Foo Bar","doc":"60170150166","value":"158.56","month":"102011","hours":"10"},{"code":"6666","name":"Foo Bar","doc":"60170150166","value":"169.81","month":"042012","hours":"10"},{"code":"6666","name":"Foo Bar","doc":"60170150166","value":"169.81","month":"052012","hours":"10"}];
const result = combine(arrayOfObject);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句