23

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?

4 Answers 4

43

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(', ')
Sign up to request clarification or add additional context in comments.

1 Comment

Lodash's pluck() has been deprecated in favour of Lodash's map().
5

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

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

Comments

4

You can use _.map or _.pluck, like this

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

or

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

Comments

4

By using Mrityunjay's answer, this is another version of the answer to convert array of string to string:

const _ = require('lodash');
const data = ['abc','xyz','123'];
const translated = _.map(data).join(', ');
console.log(`result: ${translated}`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.