Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用唯一代码对对象数组进行分组?_Javascript - Fatal编程技术网

Javascript 如何使用唯一代码对对象数组进行分组?

Javascript 如何使用唯一代码对对象数组进行分组?,javascript,Javascript,我有一个对象数组(示例): 如何循环数组中的每个元素,如果当前元素的“行标签”代码与下一个元素的“行标签”代码匹配,则将该ProdCode&Desc添加到当前元素ProdCode&Desc的末尾,每个字符串用分号分隔 上述示例的预期输出为: [ { 'Row Labels': '37383783738', 'ProdCode&Desc': '8H9H89 Homestyle cinnamon cake (200g)8x120; 9HD063 Goodness me

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

如何循环数组中的每个元素,如果当前元素的“行标签”代码与下一个元素的“行标签”代码匹配,则将该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"]);
  }
});

您可以使用数组方法来完成

const数据=[
{
“行标签”:“37383783738”,
“产品代码和说明”:“8H9H89家庭式肉桂蛋糕(200g)8x120”,
},
{
“行标签”:“37383783738”,
“产品代码和描述”:“9HD063天哪!烤肉片(20g)6x30”,
},
{
“行标签”:“833223733”,
“产品代码和说明”:“39HSH02 MDS烧烤辛辣(40克)2x30”,
},
{
“行标签”:“833223733”,
“产品代码和说明”:“93JSHS珍藏的倾斜圆角(120g)6x30”,
},
];
const ret=Object.values(
数据减少((上一个,c)=>{
常数p=上一个;
const key=c['行标签'];
如果(!p[key])p[key]={…c};
其他的
p[键]={
…p[键],
'ProdCode&Desc':(p[key]['ProdCode&Desc']+=`;${c['ProdCode&Desc']}`),
};
返回p;
}, {})
);

控制台日志(ret)太棒了!谢谢你,hr先生。我真的应该花点时间来学习。reduce和它的全部功能。是否仍然可以按照我在预期输出示例中所述的方式返回数据?@Perry,对不起,我的错误。我已经更新了代码。现在检查一下,一切正常。再次感谢。
records.map((record, index, array) => {
   if (record["Row Labels"]
   .toLowerCase()
   .includes(array[index + 1]["Row Lables"].toLowerCase())
) {
   record.push(array[index + 1]["ProdCode&Desc"]);
  }
});