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

Concatenate specific keys within condition – JavaScript Object

I’ve got this type of dataset :

[
  {
    CODMAT: '86        ',
    LIBMAT: 'Chariot N.50 Damien           ',
    CODCAR: 'I050DCHE  ',
    ZONLST: 'A',
    ALLLST: 1,
    CIRMAT1: 'AUA',
    CIRMAT2: 'SUC',
    CIRMAT3: 'SAL',
    CIRMAT4: 'AU3',
    CIRMAT5: '   ',
    CIRMAT6: '   '
  },
  {
   ...
  }
]

I would like to concatenate all the ‘CIRMAT‘ data and delete these which are empty, like this :

  {
    CODMAT: '86        ',
    LIBMAT: 'Chariot N.50 Damien           ',
    CODCAR: 'I050DCHE  ',
    ZONLST: 'A',
    ALLLST: 1,
    CIRMAT: ['AUA','SUC','SAL','AU3']
  }

Thanks for your help

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

>Solution :

This should work :

    const data = [
      {
        CODMAT: '86        ',
        LIBMAT: 'Chariot N.50 Damien           ',
        CODCAR: 'I050DCHE  ',
        ZONLST: 'A',
        ALLLST: 1,
        CIRMAT1: 'AUA',
        CIRMAT2: 'SUC',
        CIRMAT3: 'SAL',
        CIRMAT4: 'AU3',
        CIRMAT5: '   ',
        CIRMAT6: '   '
      },
    ]

    const output = input.map(item => (
      Object.entries(item).reduce((formatted, [key, value]) => {
        if(key.startsWith("CIRMAT") && typeof value === "string"){
          if(value.trim().length === 0) return formatted;
          if(!formated.CIRMAT) formatted.CIRMAT = [value];
          else formatted.CIRMAT.push(value); 
        }
        else{
          formatted[key] = value;
        }
        return formatted;
      }, {})
    ))
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