如何通过唯一代码对对象数组进行分组?

我有一个对象数组(示例):


[

  {

     '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"]);

  }

});


森栏
浏览 108回答 1
1回答

尚方宝剑之说

您可以使用数组归约方法来做到这一点。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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript