unwrap
rel.unwrap([:attr])rel.unwrap([:attr1, :attr2])rel.unwrap('attr')Problem
Section titled “Problem”Flatten nested Hash/object attributes into top-level tuple attributes.
Example: I have tuples with nested address hashes, and I want to flatten them into individual columns.
Description
Section titled “Description”The unwrap operator takes tuples containing Hash/object-valued attributes and flattens them, promoting the nested keys to top-level attributes. This is the inverse of a wrap operation.
Given a tuple like { name: "Alice", address: { city: "London", country: "UK" } }, unwrapping the address attribute produces { name: "Alice", city: "London", country: "UK" }.
Multiple attributes can be unwrapped in a single operation by passing an array of attribute names.
Pass the attribute name as a string to unwrap.
Requirements
Section titled “Requirements”The specified attributes must contain Hash/object values.
Examples
Section titled “Examples”Basic unwrap
Section titled “Basic unwrap”wrapped = Bmg::Relation.new([ { id: 1, name: "Alice", address: { city: "London", country: "UK" } }, { id: 2, name: "Bob", address: { city: "Paris", country: "France" } }, { id: 3, name: "Carol", address: { city: "Berlin", country: "Germany" } }])
wrapped.unwrap([:address]).to_a
=>[{:id=>1, :name=>"Alice", :city=>"London", :country=>"UK"}, {:id=>2, :name=>"Bob", :city=>"Paris", :country=>"France"}, {:id=>3, :name=>"Carol", :city=>"Berlin", :country=>"Germany"}]const wrapped = Bmg([ { id: 1, name: "Alice", address: { city: "London", country: "UK" } }, { id: 2, name: "Bob", address: { city: "Paris", country: "France" } }, { id: 3, name: "Carol", address: { city: "Berlin", country: "Germany" } }])
wrapped.unwrap('address').toArray()
// =>// [{ id: 1, name: "Alice", city: "London", country: "UK" },// { id: 2, name: "Bob", city: "Paris", country: "France" },// { id: 3, name: "Carol", city: "Berlin", country: "Germany" }]Comparison with ungroup
Section titled “Comparison with ungroup”unwrap and ungroup both flatten nested data, but they work differently:
| Operator | Input | Output |
|---|---|---|
unwrap | Hash/object attribute {a: {x: 1, y: 2}} | Flat tuple {x: 1, y: 2} (1 tuple out) |
ungroup | Relation/array attribute {a: [{x: 1}, {x: 2}]} | Multiple tuples (N tuples out) |
- Use
unwrapfor Hash/object attributes (one-to-one flattening) - Use
ungroupfor Relation/array attributes (one-to-many flattening)