Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining property values of objects in an array

Tags:

I have an array of objects. The objects have a property called userName. Is there a way to concatenate the userName values into a comma delimited string? I assume I can use the join function but the only way I can think of takes two steps.

var userNames: string[]; objectArr.forEach((o) => { userNames.push(o.userName); }); var userNamesJoined = userNames.join(","); 

Is there a way to do it in one line of code?

like image 693
nthpixel Avatar asked Jul 25 '14 00:07

nthpixel


1 Answers

Use map instead of forEach and drop the parenthesis and the curly braces in the lambda:

var userNames = objectArr.map(o => o.userName).join(', ');

like image 138
Nikola Dimitroff Avatar answered Oct 04 '22 01:10

Nikola Dimitroff