Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine objects in array in Javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading