Javascript 使用 AngularJS 和 Lodash 将数组转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27605014/
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
Array to string with AngularJS and Lodash
提问by Eric Mitjans
I have an array ($scope.paxlist) looking like this:
我有一个如下所示的数组 ($scope.paxlist):
[
{"name":"Maria","chosen":false},
{"name":"Jenny","chosen":false},
{"name":"Ben","chosen":false},
{"name":"Morris","chosen":false}
]
I need to take only the values from nameand convert them into a string in order to be able to use ng-CSV properly.
The desired output would be something like this:
我只需要从中获取值name并将它们转换为字符串,以便能够正确使用 ng-CSV。所需的输出将是这样的:
$scope.var = "Maria, Jenny, Ben, Morris"
Taking into consideration that I have Angular and Lodash already loaded, could anybody point out if they have already some tool to do this painlessly?
考虑到我已经加载了 Angular 和 Lodash,有人能指出他们是否已经有一些工具可以轻松地做到这一点吗?
回答by Mritunjay
Using native mapof javascript you can do it as bellow
使用JavaScript 的原生地图,您可以按照以下方式进行
var data = [
{"name":"Maria","chosen":false},
{"name":"Jenny","chosen":false},
{"name":"Ben","chosen":false},
{"name":"Morris","chosen":false}
];
data.map(function(obj){return obj.name;}).join(', '); // returns the expected output.
Using Lodash
使用 Lodash
_.map(data,'name').join(', ')
回答by Felix Kling
回答by Alexander T.
回答by S.Mishra
By using Mrityunjay's answer, this is another version of the answer to convert array of string to string:
通过使用 Mrityunjay 的答案,这是将字符串数组转换为字符串的另一个版本的答案:
const _ = require('lodash');
const data = ['abc','xyz','123'];
const translated = _.map(data).join(', ');
console.log(`result: ${translated}`);

