我有一个名为分组
的对象:
{ '1':
[ { id: 1,
name: 'John Doe',
supplierName: 'Sup1',
count: '21' } ],
'2':
[ { id: 2,
name: 'Jane Doe',
supplierName: 'Sup1',
count: '95' } ],
'3':
[ { id: 3,
name: 'Paul',
supplierName: 'Sup1',
count: '2' },
{ id: 3,
name: 'Paul',
supplierName: 'Sup2',
count: '1' }
]
}
我用这个创建一个用户对象:
let users = _.map(grouped, userArray => ({
id: userArray[0].id,
name: userArray[0].name,
suppliers: _.reduce(userArray, (accumulated, supplierObj) => {
if (supplierObj.supplierName) {
accumulated.push({
title: supplierObj.supplierName,
});
}
return accumulated;
}, []),
}));
目前看起来像这样:
{
"users": [
{
"id": 1,
"name": "John Doe",
"suppliers": [
{
"title": "Sup1"
}
]
},{
"id": 2,
"name": "Jane Doe",
"suppliers": [
{
"title": "Sup1"
}
]
},{
"id": 3,
"name": "Paul",
"suppliers": [
{
"title": "Sup1"
},{
"title": "Sup2"
}
]
}
]
}
我现在想添加 count
,我的输出如下所示:
{
"users": [
{
"id": 1,
"name": "John Doe",
"count": "21",
"suppliers": [
{
"title": "Sup1"
}
]
},{
"id": 2,
"name": "Jane Doe",
"count": "95",
"suppliers": [
{
"title": "Sup1"
}
]
},{
"id": 3,
"name": "Paul",
"count": "2",
"suppliers": [
{
"title": "Sup1"
},{
"title": "Sup2"
}
]
}
]
}
如果我简单地添加 count: userArray[0].count
,对于拥有单个 vendor 的每个用户,我的输出都是正确的,但对于拥有多个 vendor 的用户,仅选择第一个。例如。对于上述情况,Paul 将显示计数为 2,对于 Paul,Sup1 有 2 个客户,Sup2 有 1 个客户。我该如何解决这个问题,以便像 Paul 这样拥有多个 vendor 的用户?
最佳答案
count: userArray.reduce((sum, user) => sum + +user.count, 0)
使用.reduce
您可以对计数进行求和。需要一元加号将字符串转换为数字。
而且不需要lodash,如果可以过滤和映射就不需要reduce:
const users = Object.values(grouped).map(users => ({
id: users[0].id,
name: users[0].name,
suppliers: users.map(user => user.supplierName).filter(it => it),
count: users.reduce((sum, user) => sum + +user.count, 0),
}));
关于javascript - 减少计数,以便显示每个用户的所有 vendor 的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56500540/