skip to Main Content

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:

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

3

Answers


  1. .map () and .join () functions should help you achieve the desired outcome. .map () can transform the array of objects to an array of strings, while .join () will convert the resulting array to a string.

    Login or Signup to reply.
  2. You can do this with the help of the .map() and .join() methods of arrays.

    For example:

    const data = [
      {
        "ID": "771276",
        "Name": "John",
        "Subject": [
          {
            "Name": "Subject 1"
          },
          {
            "Name": "Subject 2"
          }
        ]
      },
      {
        "ID": "771277",
        "Name": "Mary",
        "Subject": [
          {
            "Name": "Subject 80"
          }
        ]
      },
    ]
    
    const result = data.map(({
      ID,
      Name,
      Subject
    }) => ({
      ID,
      Name,
      Subject: Subject.map(sub => sub.Name).join(', ')
    }))
    
    console.log("Result", result);
    Login or Signup to reply.
  3. In js is quiete simple, apply to your code and leave a comment if something is not clear!

    data["Subject"].map(subject => subject["Name"]).join(", ");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search