0

I have object, which has field id and text and possibly more other fields.

There are lots of objects in the array, and I want to convert it to a text array.

This is what I have at the moment. Any prettier solution, possible something LINQ like?

var emails = new Array();
angular.forEach(this.form.Emails, function (email) {
    emails.push(email.text);
});
Jaanus
  • 16,161
  • 49
  • 147
  • 202
  • You could use something like `underscore` and use their `map()` functions. Another interesting choice can be seen here: http://stackoverflow.com/questions/15411620/angular-equivalent-of-jquery-map – Nix Apr 24 '14 at 11:39
  • What is the problem with solution you posted above? – Maxim Shoustin Apr 24 '14 at 11:44
  • Extra 3 lines of code everytime I have to select a field from object array. – Jaanus Apr 29 '14 at 06:49

1 Answers1

1

Like @Nix answered you, you can use pluck of Underscore library.

extracting a list of property values


Example:

this.form.Emails = [
                    {text: 'moe', id: 1},
                    {text: 'larry', id: 2},
                    {text: 'curly', id: 3}
                   ];

var emails = _.pluck(this.form.Emails, 'text');

//ouput
 ["moe", "larry", "curly"]

Anyways I suggest you to leave your code version as is (aka angular.forEach). Because other programmer that maintains your code must know what pluck does.

Make your code simple

Community
  • 1
  • 1
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225