gpt4 book ai didi

javascript - 通过相同的属性联合对象并通过同一数组中的不同属性连接

转载 作者:行者123 更新时间:2023-11-30 14:14:43 26 4
gpt4 key购买 nike

我得到这个数组,想在代码、名称、文档和值的值都相等时连接对象,并连接月份和小时。我尝试使用 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>

关于javascript - 通过相同的属性联合对象并通过同一数组中的不同属性连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53781599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com