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

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在給定數(shù)組中僅添加具有相同 _id 的 sumdigit 列值

如何在給定數(shù)組中僅添加具有相同 _id 的 sumdigit 列值

翻翻過去那場雪 2022-12-02 16:45:20
輸入數(shù)組=>[{_id: "555", sumdigit: 1000,  Price: 1000}{_id: "677", sumdigit: 10,  Price: 320} {_id: "555", sumdigit: 170, Price: 1000}  {_id: "444", sumdigit: 10,  Price: 1000} {_id: "400", sumdigit: 10,  Price: 320}]輸出數(shù)組=>[{_id: "555", sumdigit: 1170,  Price: 1000},{_id: "677", sumdigit: 10,  Price: 320},{_id: "444", sumdigit: 10,  Price: 1000}, {_id: "400", sumdigit: 10,  Price: 320}]
查看完整描述

3 回答

?
素胚勾勒不出你

TA貢獻(xiàn)1827條經(jīng)驗 獲得超9個贊

這是你想要的:


const a = [{ _id: "555", sumdigit: 1000, Price: 1000 }, { _id: "677", sumdigit: 10, Price: 320 }, { _id: "555", sumdigit: 170, Price: 1000 }, { _id: "444", sumdigit: 10, Price: 1000 }, { _id: "400", sumdigit: 10, Price: 320 }];


console.log([...a.reduce((a, c) => {

    if (a.has(c._id)) {

        a.get(c._id).sumdigit += c.sumdigit;

    } else {

        a.set(c._id, c);

    }

    return a;

}, new Map()).values()])


查看完整回答
反對 回復(fù) 2022-12-02
?
動漫人物

TA貢獻(xiàn)1815條經(jīng)驗 獲得超10個贊

您可以使用 reduce 來累積值


const arrays=[{_id: "555", sumdigit: 1000,  Price: 1000}, {_id: "677", sumdigit: 10,  Price: 320} , {_id: "555", sumdigit: 170, Price: 1000} , {_id: "444", sumdigit: 10,  Price: 1000} , {_id: "400", sumdigit: 10,  Price: 320}]


 res=arrays.reduce((acc,{_id,sumdigit,Price}) => {

   if(!acc[_id]) acc[_id] = {...acc[_id],_id,sumdigit,Price}

   else acc[_id] = {...acc[_id],_id:_id,

                   sumdigit : acc[_id].sumdigit + sumdigit,Price:Price}

   return acc

 },{})

 console.log(Object.values(res))


查看完整回答
反對 回復(fù) 2022-12-02
?
當(dāng)年話下

TA貢獻(xiàn)1890條經(jīng)驗 獲得超9個贊

您可以通過迭代input array檢查 _id 是否在輸出中以增加sumdigit屬性來創(chuàng)建輸出。


試試這段代碼。


const input = [

  {_id: "555", sumdigit: 1000,  Price: 1000},

  {_id: "677", sumdigit: 10,  Price: 320},

  {_id: "555", sumdigit: 170, Price: 1000},

  {_id: "444", sumdigit: 10,  Price: 1000},

  {_id: "400", sumdigit: 10,  Price: 320},

]



const output = [];


// Iterate over the input array

for (let i = 0; i < input.length; i++) {

  const element = input[i];


  // Check if the id is already present in the output variable

  const prevObjectIdx = output.findIndex(obj => obj._id === element._id);


  /**

   * If the id is already into the output array just increase the subdigit with the other one.

   * Otherwise, just add the element into the output variable.

   */

  if (prevObjectIdx !== -1) {

    output[prevObjectIdx].sumdigit += element.sumdigit;

  } else {

    output.push(element);

  }

};



console.log(output)


查看完整回答
反對 回復(fù) 2022-12-02
  • 3 回答
  • 0 關(guān)注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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