nthpixel
nthpixel

Reputation: 3109

Joining property values of objects in an array

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?

Upvotes: 22

Views: 25085

Answers (1)

Nikola Dimitroff
Nikola Dimitroff

Reputation: 6237

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

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

Upvotes: 53

Related Questions