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

How to convert to String a elements of each object from an array?

I have an array of object, like this:

[
    {
        "ID": "771276",       
        "Name": "John",        
        "Subject": [
            {
                "Name": "Subject 1"
            },
            {
                "Name": "Subject 2"
            }
        ]
    },
        {
        "ID": "771277",       
        "Name": "Mary",        
        "Subject": [
            {
                "Name": "Subject 80"
            }
        ]
    },
    .....   
]

How can I convert Subject element from each object to a String with elements separated by comma?

Getting the first object as example, I hope the result:

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

{
    "ID": "771276",       
    "Name": "John",        
    "Subject": "Subject 1, Subject 2"
}

>Solution :

You can make this happen with the help of map and join functions in javascript.

Below is code snippet.

const tryObj = [{
    "ID": "771276",
    "Name": "John",
    "Subject": [{
        "Name": "Subject 1"
      },
      {
        "Name": "Subject 2"
      }
    ]
  },
  {
    "ID": "771277",
    "Name": "Mary",
    "Subject": [{
      "Name": "Subject 80"
    }]
  },
]
const check = tryObj.map(({
  ID,
  Name,
  Subject
}) => ({
  ID,
  Name,
  Subject: Subject.map(sub => sub.Name).join(', ')
}))
console.log("all together", check);
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