我想添加共同属性,即同一个键的total_quantity_sold,并将其作为总数附加到父索引。
这是我的产品阵列
{ '900001':
[ anonymous {
id: '900001',
name: 'Pack1',
product: 2017-11-02T13:49:25.596Z,
total_quantity_sold: '1' },
anonymous {
id: '900001',
name: 'Pack1',
product: 2018-02-11T13:49:25.596Z,
total_quantity_sold: '4' },
anonymous {
id: '900001',
name: 'Pack1',
product: 2017-12-02T13:49:25.596Z,
total_quantity_sold: '1' } ],
'900002':
[ anonymous {
id: '900002',
name: 'Pack2',
product: 2018-01-02T13:49:25.596Z,
total_quantity_sold: '1' },
anonymous {
id: '900002',
name: 'Pack2',
product: 2017-11-02T13:49:25.596Z,
total_quantity_sold: '1' },
anonymous {
id: '900002',
name: 'Pack2',
product: 2018-02-11T13:49:25.596Z,
total_quantity_sold: '4' } ],}
我想对所有数量求和并将其与父键相加,以便我的最终数组看起来像这样。实际上我想要填充图形所需的总计数和每个日期的计数。
{ '900001':
'total' : 6
[ {
name: 'Pack1',
product: 2017-11-02T13:49:25.596Z,
total_quantity_sold: '1' },
{
name: 'Pack1',
product: 2018-02-11T13:49:25.596Z,
total_quantity_sold: '4' },
{
name: 'Pack1',
product: 2017-12-02T13:49:25.596Z,
total_quantity_sold: '1' } ],
'900002':
'total' : 7
[ {
name: 'Pack2',
product: 2018-01-02T13:49:25.596Z,
total_quantity_sold: '2' },
{
name: 'Pack2',
product: 2017-11-02T13:49:25.596Z,
total_quantity_sold: '1' },
{
name: 'Pack2',
product: 2018-02-11T13:49:25.596Z,
total_quantity_sold: '4' } ],}
谢谢
答案 0 :(得分:2)
当然可以!您可以通过遍历哈希表中的每个条目来完成此操作,并将其替换为您希望 就地 的目标对象。我们还可以使用简单的缩减器来获得 quantities sold
的总和!
Object.entries(obj).forEach(a => {
const [key, children] = a
const total = children.reduce((p,c) => p+c.total_quantity_sold, 0)
obj[key] = {total, children}
})