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.
我有一个对象数组。对象具有一个名为userName的属性。是否有办法将用户名值连接到一个逗号分隔的字符串中?我假设我可以使用join函数,但是我能想到的唯一方法是执行两个步骤。
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 个解决方案
#1
28
Use map
instead of forEach
and drop the parenthesis and the curly braces in the lambda:
用map代替forEach,去掉括号和花括号:
var userNames = objectArr.map(o => o.userName).join(', ');
var用户名= objectArr。地图(o = > o.userName)。加入(" ");
#1
28
Use map
instead of forEach
and drop the parenthesis and the curly braces in the lambda:
用map代替forEach,去掉括号和花括号:
var userNames = objectArr.map(o => o.userName).join(', ');
var用户名= objectArr。地图(o = > o.userName)。加入(" ");