Reputation: 491
I am trying to filter through an array of mashes(pseudo-objects using the Hashie::Mash gem) containing pages with parent_id's and self_id's. In this function I would like to create a new hash where I can index the children objects by the parent objects.
Here's what I'm trying:
(A parent object has a parent_id
equal to zero.)
('hashies' is an array containing Hashie::Mash objects that have the page_id attributes)
page_hash = Hash[hashies.map { |page|
if page.parent_id != "0" then [page.id, page] else [page.parent_id, page] end
}]
My desired output would be something as follows:
page_hash = {
#<Hashie::Mash id="978835" parent_id="0"> => [
#<Hashie::Mash id="980705" parent_id="978835">,
#<Hashie::Mash id="1049260" parent_id="978835">
]
}
But instead, it seems I'm just altering the Hashie::Mash objects themselves, and changing their parent_id's and id's. Here's my actual output:
page_hash = {
#<Hashie::Mash id="1049100" parent_id="1044858"> =>
#<Hashie::Mash id="1049100" parent_id="1044858">
}
Upvotes: 0
Views: 1487
Reputation: 23949
Try something like this:
by_id = hashies.group_by(&:id)
page_hash = hashies.group_by { |page| by_id[page.parent_id] }
Upvotes: 0