亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

如何通過唯一代碼對對象數組進行分組?

如何通過唯一代碼對對象數組進行分組?

森欄 2023-11-12 14:25:04
我有一個對象數組(示例):[  {     'Row Labels': '37383783738',     'ProdCode&Desc': '8H9H89 Homestyle cinnamon cake (200g) 8x120',  },        {     'Row Labels': '37383783738',     'ProdCode&Desc': '9HD063 Goodness me! Chargrilled bites (20g) 6x30',  },        {     'Row Labels': '83322223733',     'ProdCode&Desc': '39HSH02 MDS Chargrilled Hot & Spicy (40g) 2x30',  },  {     'Row Labels': '83322223733',     'ProdCode&Desc': '93JSHS Treasured battered fillet (120g) 6x30',  },]如何循環遍歷數組中的每個元素,并且如果當前元素的“行標簽”代碼與下一個元素的“行標簽”代碼匹配 - 則將該 ProdCode&Desc 添加到當前元素 ProdCode&Desc 的末尾,每個字符串由半角分隔冒號。上面示例的預期輸出為:[  {     'Row Labels': '37383783738',     'ProdCode&Desc': '8H9H89 Homestyle cinnamon cake (200g)8x120; 9HD063 Goodness me! Chargrilled bites (20g) 6x30',  },             {     'Row Labels': '83322223733',     'ProdCode&Desc': '39HSH02 MDS Chargrilled Hot & Spicy (40g) 2x30; 93JSHS Treasured battered fillet (120g) 6x30',  },]這是我到目前為止所擁有的:records.map((record, index, array) => {   if (record["Row Labels"]   .toLowerCase()   .includes(array[index + 1]["Row Lables"].toLowerCase())) {   record.push(array[index + 1]["ProdCode&Desc"]);  }});
查看完整描述

1 回答

?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

您可以使用數組歸約方法來做到這一點。

const data = [

? {

? ? 'Row Labels': '37383783738',

? ? 'ProdCode&Desc': '8H9H89 Homestyle cinnamon cake (200g) 8x120',

? },

? {

? ? 'Row Labels': '37383783738',

? ? 'ProdCode&Desc': '9HD063 Goodness me! Chargrilled bites (20g) 6x30',

? },

? {

? ? 'Row Labels': '83322223733',

? ? 'ProdCode&Desc': '39HSH02 MDS Chargrilled Hot & Spicy (40g) 2x30',

? },

? {

? ? 'Row Labels': '83322223733',

? ? 'ProdCode&Desc': '93JSHS Treasured battered fillet (120g) 6x30',

? },

];


const ret = Object.values(

? data.reduce((prev, c) => {

? ? const p = prev;

? ? const key = c['Row Labels'];

? ? if (!p[key]) p[key] = { ...c };

? ? else

? ? ? p[key] = {

? ? ? ? ...p[key],

? ? ? ? 'ProdCode&Desc': (p[key]['ProdCode&Desc'] += `; ${c['ProdCode&Desc']}`),

? ? ? };

? ? return p;

? }, {})

);

console.log(ret);



查看完整回答
反對 回復 2023-11-12
  • 1 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號