Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array to string with AngularJS and Lodash

Tags:

I have an array ($scope.paxlist) looking like this:

[    {"name":"Maria","chosen":false},    {"name":"Jenny","chosen":false},    {"name":"Ben","chosen":false},    {"name":"Morris","chosen":false} ] 

I need to take only the values from name and convert them into a string in order to be able to use ng-CSV properly. The desired output would be something like this:

$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?

like image 924
Eric Mitjans Avatar asked Dec 22 '14 14:12

Eric Mitjans


2 Answers

Using native map of javascript you can do it as bellow

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

_.map(data,'name').join(', ') 
like image 121
Mritunjay Avatar answered Sep 20 '22 01:09

Mritunjay


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

$scope.var = _.pluck($scope.paxlist, 'name').join(', '); 
like image 44
Felix Kling Avatar answered Sep 19 '22 01:09

Felix Kling