-2

I have an array like this, which will the response from the API.

[
    {
        "id": "F1eOrsr3g7gad6",
        "created_at": 1591951315,
        "url": "https://example.com",
        "secret": "1234",
        "secret_exists": true
    },
    {
        "id": "FintcvTBaYwPz2",
        "created_at": 1591953315,
        "url": "http://example.com",
        "secret": "34532",
        "secret_exists": true
    }
]

How do I check this array has the value "F1eOrsr3g7gad6" or not?

I had tried to write a function that will return the index value if the value exists.

func isExists(key string, value string, data []map[string]interface{}) (result int) {
    result = -1
    for i, search := range data {
        if search[key] == value {
            result = i
            break
        }
    }
    return result
}
var value string = "FintcvTBaYwPz2"
var key string = "id"
result := isExists(key, value, data) // here data will be the array which I want to pass.
fmt.Println("Result: ", result)
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
ManuGN
  • 21
  • 4

1 Answers1

0

You've done all the hard work, just change the signature of your function to return a bool instead of the index, and return true or false:

func isExists(key string, value string, data []map[string]interface{}) (exists bool) {

    for _, search := range data {
        if search[key] == value {
            return true
        }
    }
    return false
}

https://play.golang.org/p/lJGwa6pZaX5

colm.anseo
  • 19,337
  • 4
  • 43
  • 52
  • Thanks @colm. I am getting this error When I pass my array of objects as a parameter in my function. `cannot convert arr (type []interface {}) to type []byte` – ManuGN Feb 09 '21 at 05:34
  • Check the playground link I included - it shows how to convert a stream of JSON bytes into a usable go data type. – colm.anseo Feb 09 '21 at 05:37