22

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?

1 Answer 1

53

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

what shoud we do if we don't want to join the empty usernames ?
@ZulqarnainJalil just filter the items before joining: objectArr.map(o => o.userName).filter(name => name).join(', ');
Can we collect more than 1 properties? Like fullName?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.