Home > Blockchain >  Combine objects in array in Javascript
Combine objects in array in Javascript

Time:05-12

I have an array of objects like follows

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'}

I want to combine those objects to get the following result (join the objects based on same analyzer_code).

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

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

How can I achieve this in Javascript?

Edit: bill_no will be same in the every object

CodePudding user response:

Apparently you want to group by bill_no and analyzer_code.

One way is to use reduce and collect groups by a key that is the combination of bill_no and analyzer_code properties. I'll use JSON.stringify to create such a key:

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);

  • Related