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);
});
3
  • You could use something like underscore and use their map() functions. Another interesting choice can be seen here: stackoverflow.com/questions/15411620/… Commented Apr 24, 2014 at 11:39
  • What is the problem with solution you posted above? Commented Apr 24, 2014 at 11:44
  • Extra 3 lines of code everytime I have to select a field from object array. Commented Apr 29, 2014 at 6:49

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

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.