I have an array that contains objects, like this:
"exams": [
{
"id": "62b30836e941368db5d0e531",
"name": "Basic",
"price": 100
},
{
"id": "62b30836e941368db5d0e532",
"name": "Full",
"price": 200
}
]
I need pick only the name property from every object, and build a string, where the elements are “separated” with comma. Like this:
"Basic,Full"
I tried the following, but the method built every whole object into the string:
var e = exams.join(",");
Advertisement
Answer
Before using the .join() to create a string, you should map the values you want from the array of objects. Like this:
exams.map(exam => exam.name)
This should return something like: ['Basic', 'Full'].
Then you do the join.
You could do all in one line (also avoid var, use const instead):
const e = exams.map(exam => exam.name).join(',')