Skip to content

Instantly share code, notes, and snippets.

@computerphysicslab
Created July 9, 2020 12:23
Show Gist options
  • Save computerphysicslab/a6cec3693d2bb1910a05b2bb7b6bd72d to your computer and use it in GitHub Desktop.
Save computerphysicslab/a6cec3693d2bb1910a05b2bb7b6bd72d to your computer and use it in GitHub Desktop.
// Loop through a map array to find the item matching by any of its keys/values
// In this example:
// [0]:
// "fruta": "manzana",
// "verdura": "coliflor"
// [1]:
// "planas": "lentejas",
// "redondas": "garbanzos"
// searching for "planas": "lentejas" yields array item [1]
//
package main
import (
"encoding/json"
"fmt"
"reflect"
)
func myDebug(s string, i interface{}) {
pretty, err := json.MarshalIndent(i, "", " ")
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("\n\nmyDebug: %s (%s) => %s\n", s, reflect.TypeOf(i).String(), string(pretty))
fmt.Printf("\n\nmyDebugPlain: %+v\n", i)
}
type Map map[string]interface{}
/**
* Devuelve el elemento de un array cuyo campo indicado tiene el valor tambien indicado.
*/
func searchInArray(theArray []Map, key string, value string) Map {
for i := range theArray {
if theArray[i][key] == value {
return theArray[i]
}
}
return Map{}
}
func main() {
mapas := make([]Map, 2)
/*
myDebug("mapas0", mapas[0])
mapas[0] = make(Map)
myDebug("mapas0", mapas[0])
myDebug: mapas0 (main.Map) => null
myDebugPlain: map[]
myDebug: mapas0 (main.Map) => {}
myDebugPlain: map[]
*/
// mapas = append(mapas, Map{})
mapas[0] = make(Map)
mapas[0]["fruta"] = "manzana"
mapas[0]["verdura"] = "coliflor"
// mapas = append(mapas, Map{})
mapas[1] = make(Map)
mapas[1]["planas"] = "lentejas"
mapas[1]["redondas"] = "garbanzos"
myDebug("mapas", mapas)
/*
myDebug: mapas ([]main.Map) => [
{
"fruta": "manzana",
"verdura": "coliflor"
},
{
"planas": "lentejas",
"redondas": "garbanzos"
}
]
myDebugPlain: [map[fruta:manzana verdura:coliflor] map[planas:lentejas redondas:garbanzos]]
*/
var result interface{}
result = searchInArray(mapas, "planas", "lentejas")
myDebug("result", result)
result = searchInArray(mapas, "redondas", "lentejas")
myDebug("result", result)
result = searchInArray(mapas, "redondas", "garbanzos")
myDebug("result", result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment