猿问

Javascript:折叠属性值上的对象数组,求和数量属性,保留最近的

寻找更实用的“功能”方式......

我有一个产品的对象看起来像这样(注意重复skuid的)

"products": [
    {
      "skuid": "B1418",
      "name": "Test Product 1",
      "price": 7,
      "lastOrderedDate": 20181114,
      "quantity": 2
    },{
      "skuid": "B3446",
      "name": "Test Product 2",
      "price": 6,
      "lastOrderedDate": 20190114,
      "quantity": 2
    },{
      "skuid": "B1418",
      "name": "Test Product 1",
      "price": 7,
      "lastOrderedDate": 20180516,
      "quantity": 5
    },{
      "skuid": "B3446",
      "name": "Test Product 2",
      "price": 6,
      "lastOrderedDate": 20180411,
      "quantity": 11
    }]

我想创建一个新的数组,每个不同的单个对象,skuid但SUMS所有的quantity值,保留最新的lastOrderedDate

最终结果如下:

"products": [
    {
      "skuid": "B1418",
      "name": "Test Product 1",
      "price": 7,
      "lastOrderedDate": 20181114,
      "quantity": 7
    },{
      "skuid": "B3446",
      "name": "Test Product 2",
      "price": 6,
      "lastOrderedDate": 20190114,
      "quantity": 13
    }]

我可以用一堆forEach和if来做,但我想学习一种更简洁的方法来做到这一点。或许有一种,那么reduce


千巷猫影
浏览 348回答 3
3回答

阿波罗的战车

您可以Map稍后获取并获取所有值作为结果集。const&nbsp; &nbsp; getGrouped = (m, o) => {&nbsp; &nbsp; &nbsp; &nbsp; var item = m.get(o.skuid);&nbsp; &nbsp; &nbsp; &nbsp; if (!item) return m.set(o.skuid, Object.assign({}, o));&nbsp; &nbsp; &nbsp; &nbsp; if (item.lastOrderedDate < o.lastOrderedDate) item.lastOrderedDate = o.lastOrderedDate;&nbsp; &nbsp; &nbsp; &nbsp; item.quantity += o.quantity;&nbsp; &nbsp; &nbsp; &nbsp; return m;&nbsp; &nbsp; };var data = { products: [{ skuid: "B1418", name: "Test Product 1", price: 7, lastOrderedDate: 20181114, quantity: 2 }, { skuid: "B3446", name: "Test Product 2", price: 6, lastOrderedDate: 20190114, quantity: 2 }, { skuid: "B1418", name: "Test Product 1", price: 7, lastOrderedDate: 20180516, quantity: 5 }, { skuid: "B3446", name: "Test Product 2", price: 6, lastOrderedDate: 20180411, quantity: 11 }] },&nbsp; &nbsp; result = Array.from(data.products&nbsp; &nbsp; &nbsp; &nbsp; .reduce(getGrouped, new Map)&nbsp; &nbsp; &nbsp; &nbsp; .values()&nbsp; &nbsp; );console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答