Skip to content

Enhance js.Object with shortcut for Slices/Maps conversion #137

Closed
@rusco

Description

@rusco

Knowing that the underlying Javascript Object is an Array or a Map I see myself repeatedly using the verbose

SomeJsObject.Interface().([]interface{}) and SomeJsObject.Interface().(map[string]interface{})

conversion to be able to iterate with the range statement.

Wouldn't it be useful to have these conversions implemented directly in js.Object ?

package main

import "github.com/gopherjs/gopherjs/js"

var console = js.Global.Get("console")

func log(val ...interface{}) {
    console.Call("log", val...)
}

func GetArray(o js.Object, id string) []interface{} /* or js.S ? */ {
    return o.Get(id).Interface().([]interface{})
}

func GetMap(o js.Object, id string) map[string]interface{} /* or js.M ? */ {
    return o.Get(id).Interface().(map[string]interface{})
}

func main() {
    g := js.Global

    //sample1:
    g.Set("S", js.S{"a", "b", "c"})
    s := GetArray(g, "S")
    for idx, val := range s {
        log(idx, val)
    }

    //sample2:
    g.Set("i", []interface{}{"d", "e", "f"})
    i := GetArray(g, "i")
    for idx, val := range i {
        log(idx, val)
    }

    //sample 3:
    g.Set("M1", map[string]interface{}{"g": 1, "h": "hi1", "i": true})
    m1 := GetMap(g, "M1")
    for key, val := range m1 {
        log(key, val)
    }

    //sample 4:
    g.Set("M2", js.M{"g": 1, "h": "hi2", "i": true})
    m2 := GetMap(g, "M2")
    for key, val := range m2 {
        log(key, val)
    }

}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions