首页 > 解决方案 > 减少和分组对象数组

问题描述

这是我的对象数组。我正在谷歌表格中编写一个自定义脚本,以接收交易数据并将其分解为一个独特项目列表,其中将订购的金额相加以创建更容易阅读的购买历史记录。

 products = [ 
      { id: 1,
        item: 'Beef',
        category: 'Meat',
        orderAmount: 5,
        caseSize: 1,
        unit: 'Lb',
        price: 50,
        supplier: 'Sysco' },
      { id: 2,
        item: 'Chicken',
        category: 'Meat',
        orderAmount: 10,
        caseSize: 2,
        unit: 'Grams',
        price: 100,
        supplier: 'Findlay' },
      { id: 3,
        item: 'Fish',
        category: 'Seafood',
        orderAmount: 15,
        caseSize: 3,
        unit: 'Lb',
        price: 40,
        supplier: 'Deodato' },
      { id: 1,    // This is an example duplicate entry
        item: 'Beef',
        category: undefined,
        orderAmount: 100,
        caseSize: 1,
        unit: 'Lb',
        price: 50,
        supplier: 'Sysco' } 
    ]

我对如何将其分解为另一个对象感到有些困惑,就像这样,其中重复的项目被删除,但重复项的 orderAmounts 被加起来。

uniqueProducts = [ 
  { id: 1,
    item: 'Beef',
    category: 'Meat',
    orderAmount: 105, //this is the altered amount
    caseSize: 1,
    unit: 'Lb',
    price: 50,
    supplier: 'Sysco' },
  { id: 2,
    item: 'Chicken',
    category: 'Meat',
    orderAmount: 10,
    caseSize: 2,
    unit: 'Grams',
    price: 100,
    supplier: 'Findlay' },
  { id: 3,
    item: 'Fish',
    category: 'Seafood',
    orderAmount: 15,
    caseSize: 3,
    unit: 'Lb',
    price: 40,
    supplier: 'Deodato' }
]

我一直在阅读有关使用 map 和 reduce 函数的信息,但我很难弄清楚如何使用如此大的对象来实现它们。

标签: javascriptarraysobjectreduce

解决方案


您可以将元素减少到 aMap并累积orderAmount

const products = [ { id: 1, item: 'Beef', category: 'Meat', orderAmount: 5, caseSize: 1, unit: 'Lb', price: 50, supplier: 'Sysco' }, { id: 2, item: 'Chicken', category: 'Meat', orderAmount: 10, caseSize: 2, unit: 'Grams', price: 100, supplier: 'Findlay' }, { id: 3, item: 'Fish', category: 'Seafood', orderAmount: 15, caseSize: 3, unit: 'Lb', price: 40, supplier: 'Deodato' }, { id: 1, item: 'Beef', category: undefined, orderAmount: 100, caseSize: 1, unit: 'Lb', price: 50, supplier: 'Sysco' } ]

const reducedProductsMap = products.reduce((map, p) => {
    const previousOrderAmount = map.get(p.id) !== undefined ? map.get(p.id).orderAmount : 0
    let newP = {...p}
    newP.orderAmount += previousOrderAmount
    map.set(newP.id, newP)

    return map
}, new Map());

console.log(Array.from(reducedProductsMap.values()));


推荐阅读