在 Javascript 中合并数组中的对象

Combine objects in array in Javascript

我有一个对象数组,如下所示

0: {bill_no: '0000633', test_code: '1', analyzer_code: '2'}

1: {bill_no: '0000633', test_code: '2', analyzer_code: '2'}

2: {bill_no: '0000633', test_code: '28', analyzer_code: '3'}

3: {bill_no: '0000633', test_code: '254', analyzer_code: '2'}

我想合并这些对象以获得以下结果(根据相同 analyzer_code 合并对象)。

0: {bill_no: '0000633', test_code: '1,2,254', analyzer_code: '2'}

1: {bill_no: '0000633', test_code: '28', analyzer_code: '3'}

如何在 Javascript 中实现此目的?

编辑:bill_no 每个对象都相同

显然你想按 bill_noanalyzer_code 分组。

一种方法是使用 reduce 并通过组合 bill_noanalyzer_code 属性的键来收集组。我将使用 JSON.stringify 创建这样一个密钥:

let data = [
  {bill_no: '0000633', test_code: '1', analyzer_code: '2'},
  {bill_no: '0000633', test_code: '2', analyzer_code: '2'},
  {bill_no: '0000633', test_code: '28', analyzer_code: '3'},
  {bill_no: '0000633', test_code: '254', analyzer_code: '2'}
];

let result = Object.values(
    data.reduce((acc, {bill_no, test_code, analyzer_code}) => {
        let key = JSON.stringify([bill_no, analyzer_code]);
        if (acc[key]) acc[key].test_code += "," + test_code
        else acc[key] = {bill_no, test_code, analyzer_code};
        return acc;
    }, {})
);

console.log(result);