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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:37:32  来源:igfitidea点击:

Joining property values of objects in an array

javascript

提问by nthpixel

I have an array of objects. The objects have a property called userName. Is there a way to concatenate the userNamevalues into a comma delimited string? I assume I can use the joinfunction 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 mapinstead of forEachand 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(', ');