我有一些对象想通过reduce进行重组,但是在找出正确的方法方面有些困难。数据如下:
DECLARE @value VARCHAR(max) = NULL
SELECT @value = COALESCE(@value + ';' + ug.unitGroupName, ug.unitGroupName)
FROM unitGroups ug
SELECT @value as Name,
MIN(ue.unitDate) as unitDate,
MIN(ue.unitStartTime) as unitStartTime,
MIN(ue.unitEndTime)as unitEndTime
FROM unitEvents ue
LEFT JOIN unitGroups ug ON ug.unitID = ue.unitID
LEFT JOIN units u ON ug.unitID = u.unitID
WHERE u.unitYear = 2018
AND ue.eventWeek between '12/1/2018' and '12/7/2018'
我想做的是重组此数组,以便按名称对所有项目进行分组,并对帐户数组进行展平。结果是这样的
[ { name: 'Item', accounts: [ { value: 1 }, { value: 2 }, { value: 3}] },
{ name: 'Item', accounts: [ { value: 1 }, { value: 2 }, { value: 3}] },
{ name: 'Item', accounts: [ { value: 1 }, { value: 2 }, { value: 3}] },
{ name: 'Item2', accounts: [ { value: 1 }, { value: 2 }, { value: 3}] },
{ name: 'Item2', accounts: [ { value: 1 }, { value: 2 }, { value: 3}] },
{ name: 'Item2', accounts: [ { value: 1 }, { value: 2 }, { value: 3}] } ],
我尝试使用以下代码来执行此操作,但是我遇到了问题,并且结构与我所寻找的不完全相同。
[
{
name: 'Item',
accounts: [ { value: 1 }, { value 2 } ] //.. Includes all account objects that had the name 'Item'
},
{
name: 'Item 2',
accounts: [ { value: 1 }, { value: 2 } ] //.. Includes all account object that had the name 'Item2'
}
]
执行此操作的正确方法是什么?
答案 0 :(得分:1)
您可以将分散的数组推入帐户,并在分组后获取对象的值。
var accounts = [{ name: 'Item', accounts: [{ value: 1 }, { value: 2 }, { value: 3 }] }, { name: 'Item', accounts: [{ value: 1 }, { value: 2 }, { value: 3 }] }, { name: 'Item', accounts: [{ value: 1 }, { value: 2 }, { value: 3 }] }, { name: 'Item2', accounts: [{ value: 1 }, { value: 2 }, { value: 3 }] }, { name: 'Item2', accounts: [{ value: 1 }, { value: 2 }, { value: 3 }] }, { name: 'Item2', accounts: [{ value: 1 }, { value: 2 }, { value: 3 }] }],
grouped = Object.values(accounts.reduce((obj, { name, accounts }) => {
obj[name] = obj[name] || { name, accounts: [] };
obj[name].accounts.push(...accounts);
return obj;
}, {}));
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }