Skip to content

Commit

Permalink
feat: Added Table.ToMapSlice
Browse files Browse the repository at this point in the history
  • Loading branch information
yokoe committed Jul 4, 2022
1 parent de542d9 commit 8b742cd
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
23 changes: 23 additions & 0 deletions table.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
15 changes: 15 additions & 0 deletions table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
}
}

0 comments on commit 8b742cd

Please sign in to comment.