javascript 将对象的属性值连接到数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24946112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Joining property values of objects in an array
提问by nthpixel
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
。有没有办法将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?
有没有办法在一行代码中做到这一点?
回答by Nikola Dimitroff
Use map
instead of forEach
and drop the parenthesis and the curly braces in the lambda:
使用map
代替forEach
并删除 lambda 中的括号和花括号:
var userNames = objectArr.map(o => o.userName).join(', ');
var userNames = objectArr.map(o => o.userName).join(', ');