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