From 0f420d2cae8b305b447574aefcccd2e74cce5d89 Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Fri, 9 Sep 2016 18:55:25 +0100 Subject: [PATCH] Add ability to get object keys and object values --- util/data/data.go | 34 ++++++++++++++++++++++++++++++++++ util/data/data_test.go | 5 +++++ 2 files changed, 39 insertions(+) diff --git a/util/data/data.go b/util/data/data.go index a5bf8747..6af5f575 100644 --- a/util/data/data.go +++ b/util/data/data.go @@ -110,6 +110,40 @@ func (d *Doc) Iff(value interface{}, path ...string) (*Doc, error) { return &Doc{nil}, d.Del(path...) } +// Keys retrieves the object keys at the specified path. +func (d *Doc) Keys(path ...string) *Doc { + + path = d.path(path...) + + out := []interface{}{} + + if m, ok := d.Get(path...).Data().(map[string]interface{}); ok { + for k, _ := range m { + out = append(out, k) + } + } + + return &Doc{out} + +} + +// Vals retrieves the object values at the specified path. +func (d *Doc) Vals(path ...string) *Doc { + + path = d.path(path...) + + out := []interface{}{} + + if m, ok := d.Get(path...).Data().(map[string]interface{}); ok { + for _, v := range m { + out = append(out, v) + } + } + + return &Doc{out} + +} + // -------------------------------------------------------------------------------- // Exists checks whether the specified path exists. diff --git a/util/data/data_test.go b/util/data/data_test.go index 595556d5..f66d451d 100644 --- a/util/data/data_test.go +++ b/util/data/data_test.go @@ -335,6 +335,11 @@ func TestOperations(t *testing.T) { // ---------------------------------------------------------------------------------------------------- + Convey("Can get object keys and vals", t, func() { + So(doc.Keys("the.item.object").Data(), ShouldResemble, []interface{}{"enabled"}) + So(doc.Vals("the.item.object").Data(), ShouldResemble, []interface{}{false}) + }) + // ---------------------------------------------------------------------------------------------------- Convey("Can get unset item", t, func() {