Suppose I have obtained relational data from a SQL database (or other source) and have two vectors of the form:
parent: Vec<P> = [a, b, c, ...];
children: Vec<C> = [a1, a2, a3, ..., b1, b2, b3, ..., c1, 2, 3, ...];
where {a1, a2, ...} belong to a, etc.; and with P
having element id
and C
having element parent_id
.
I would like to output a nested data structure of the form Vec<Pc>
where Pc
has a vector field children
(for example this might be serialized to json something like:)
[
{
"id": 1,
"children": [ { ... }, ... ]
},
...
]
What is the most idiomatic and parsimonious way to join the children with parents, assuming children is already sorted by parent_id
?
One possibility is:
for p in parents.iter() {
parents_with_children
.push(Pc::new(p, children.iter().filter(|c| c.parent_id == p.id));
}
But the disadvantage is that the entire list of children needs to be repeatedly scanned p.len()
times.
Is there another way to do this , ideally using some standard iterator function(s), that scans the children list only once at most?
(I acknowledge that the SQL layer itself could do the joining but please take it as a requirement for purposes of this question that this is not possible or desireable due to other constraints)