第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

按javascript中的字典列表分組

按javascript中的字典列表分組

慕運(yùn)維8079593 2021-11-18 20:57:01
輸入 =[{id: 13, display_name: "Customizable Desk (Aluminium, Black)", quantity: 4, unit_price: "800.40", discount: 0, price: "3201.60"},{id: 40, display_name: "Magnetic Board", quantity: 2, unit_price: "1.98", discount: 0, price: "3.96"},{id: 40, display_name: "Magnetic Board", quantity: 1, unit_price: "1.98", discount: 0, price: "1.98"},{id: 40, display_name: "Magnetic Board", quantity: 1, unit_price: "1.98", discount: 0, price: "1.98"}]輸出 =[{id: 13, display_name: "Customizable Desk (Aluminium, Black)", quantity: 4, unit_price: "800.40", discount: 0, price: "3201.60"},{id: 40, display_name: "Magnetic Board", quantity: 4, unit_price: "1.98", discount: 0, price: "7.92"}]我能夠得到一個(gè)答案,但我的過程非常漫長(zhǎng),我需要使用一些 javascript 的預(yù)定義函數(shù)來簡(jiǎn)短回答它。
查看完整描述

2 回答

?
ABOUTYOU

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊

我會(huì)做這樣的事情:


function groupProducts( input ) {

   var productsById = input.reduce( function( current, item ) {

       if( !current[ item.id ] ) {

          current[ item.id ] = [];

       }

       current[ item.id ].push( item );

       return current;

   }, {} );


   return Object.keys( productsById ).map( function( id ) {

       productsById[ id ].reduce( function( current, item ) {

           if( current ) {

              // this could be extracted as a closure passed in to coalesce items together.  Your rules for how that happens go here.

              current.quantity += item.quantity;

              current.price += item.price;

              return current;

           } else {

              return Object.assign( {}, item );  // shallow copy beware

           }

       }, null );

   } );

}

PS 我注意到在您的輸入示例中,數(shù)量和價(jià)格等內(nèi)容是字符串而不是數(shù)字。我將假設(shè)您知道如何理順這些事情,以便數(shù)據(jù)具有正確的數(shù)據(jù)類型。如果您有這些字符串,這將不起作用。


查看完整回答
反對(duì) 回復(fù) 2021-11-18
?
墨色風(fēng)雨

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊

這是執(zhí)行此操作的一種簡(jiǎn)短方法(基于我之前引用的假設(shè),這quantity是每個(gè)具有相同id值的項(xiàng)目唯一可以變化的):


inputArray.reduce((result, item) => {

  if (result.map.has(item.id)) {

    result.map.get(item.id).quantity += item.quantity;

  } else {

   result.array.push(item);

   result.map.set(item.id, item);

  }

  return result;

}, {map: new Map(), array: []}).array

reduce如果您不熟悉它,這將使用數(shù)組函數(shù)。這可以在沒有 的情況下完成Map,但這比搜索整個(gè)結(jié)果數(shù)組以查找id已經(jīng)看到的值更有效。


此代碼背后的想法是,您保留您看到的第一個(gè)項(xiàng)目,該項(xiàng)目具有id您以前從未見過的項(xiàng)目,如果您以前看過一個(gè)id項(xiàng)目,則查找該原始項(xiàng)目,并將新數(shù)量添加到之前的數(shù)量上。


查看完整回答
反對(duì) 回復(fù) 2021-11-18
  • 2 回答
  • 0 關(guān)注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)