Last active
August 11, 2020 15:31
-
-
Save pedrobertao/11478bfd792b36408055634857c6437e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"reflect" | |
"os" | |
) | |
// Find an object in a slice comparing a KEY (string) and its VALUE (interface{}) | |
func findByKey(objArr interface{}, key string, value interface{}) interface{} { | |
if reflect.TypeOf(objArr).Kind() == reflect.Slice { | |
arr := reflect.ValueOf(objArr) | |
for i := 0; i < arr.Len(); i++ { | |
currVal := arr.Index(i) | |
if currVal.FieldByName(key).Interface() == value { | |
return currVal.Interface() | |
} | |
} | |
} | |
return nil | |
} | |
type RandomType struct { | |
Name string `json:"name"` | |
ID int `json:"int"` | |
} | |
func main() { | |
var arrayOfRandom = []RandomType{ | |
RandomType{ | |
Name: "Pedro", | |
ID: 1, | |
}, | |
RandomType{ | |
Name: "Bertao", | |
ID: 2, | |
}, | |
} | |
found := findByKey(arrayOfRandom, "Name", "Pedro") | |
if found != nil { | |
log.Println("Found ID: ", found.(RandomType).ID) | |
log.Println("Found Name: ", found.(RandomType).Name) | |
} | |
os.Exit(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment