diff --git a/table.go b/table.go index 75d45dd..af5e5b5 100644 --- a/table.go +++ b/table.go @@ -195,3 +195,26 @@ func (t *Table) ToMap() map[string]interface{} { } return m } + +// ToMapSlice returns a slice of map from table values. +func (t *Table) ToMapSlice() []map[string]interface{} { + if t.rows <= 1 || t.cols == 0 { + return nil + } + + header := []string{} + for col := 0; col < t.cols; col++ { + header = append(header, t.GetStringValue(0, col)) + } + + objects := []map[string]interface{}{} + for row := 1; row < t.rows; row++ { + m := map[string]interface{}{} + for col := 0; col < t.cols; col++ { + m[header[col]] = t.GetValue(row, col) + } + objects = append(objects, m) + } + + return objects +} diff --git a/table_test.go b/table_test.go index a0b25cf..78f3198 100644 --- a/table_test.go +++ b/table_test.go @@ -245,3 +245,18 @@ func TestTableToMapConversion(t *testing.T) { t.Errorf("m[bar] = %v, want 123", m["bar"]) } } + +func TestTableToMapSliceConversion(t *testing.T) { + tb := NewTable(3, 3) + tb.PutValuesAtRow(0, "first_name", "last_name", "city") + tb.PutValuesAtRow(1, "John", "Smith", "London") + tb.PutValuesAtRow(2, "Peter", "Brown", "New York") + + rows := tb.ToMapSlice() + if rows[0]["first_name"] != "John" { + t.Errorf("row[0][first_name] = %v, want John", rows[0]["first_name"]) + } + if rows[1]["last_name"] != "Brown" { + t.Errorf("row[1][last_name] = %v, want Brown", rows[1]["last_name"]) + } +}