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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:22:34  来源:igfitidea点击:

Array to string with AngularJS and Lodash

javascriptangularjslodash

提问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

Lodash offers _.pluckto extract a property from a list of objects:

Lodash 提供_.pluck从对象列表中提取属性:

$scope.var = _.pluck($scope.paxlist, 'name').join(', ');

回答by Alexander T.

You can use _.mapor _.pluck, like this

您可以使用_.map_.pluck,像这样

$scope.var = _.map($scope.paxlist, 'name').join(', ');

or

或者

$scope.var = _.pluck($scope.paxlist, 'name').join(', ');

回答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}`);