为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

森栏 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 关注
  • 60 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信