Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over Array of Objects and Return Attributes

I am trying to return a list of titles of objects in Rails, however I keep getting the entire object returned instead of the title attribute.

loe is the object which has an attribute which is a list of articles (named article), each article is itself an object with an attribute called title.

<%= loe.article.each { |x| print x.title } %>

is how I am currently attempting to do the iteration, but this returns the entire list of articles.

like image 673
BWStearns Avatar asked Jun 03 '13 22:06

BWStearns


People also ask

Which method is used to iterate over arrays and objects?

Use Array#forEach method for array iteration.

How do you iterate over the properties of objects?

Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object.

How do you iterate over object keys and values?

You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.

Which loop is used for array of objects?

A for loop can be used to access every element of an array. The array begins at zero, and the array property length is used to set the loop end.


2 Answers

Use Array#map to invoke the title method on each and create a new array with the results:

loe.article.map(&:title)

The above is shorthand for

loe.article.map{ |o| o.title }
like image 116
Phrogz Avatar answered Sep 22 '22 01:09

Phrogz


Using the ERB tag like '<%= ' means that you're asking ERB to display the result of that expression (above and beyond the fact that you're calling print inside the block). And a call to an Enumerable method like each will return the original array, which is what you're seeing.

Change the tag to <% (remove the =) and you should be good to go.

like image 26
Cody Caughlan Avatar answered Sep 21 '22 01:09

Cody Caughlan