简体   繁体   中英

Slice by value of array

How to slice array by id

{
  "id": 1
  "status": "available" 
  "snapshot_id" : 1
  ...
},
{
   "id": 2
   "status" "non available"
   "snapshot_id" : 0
   ...
}

I didn't take it from Database or something. Need to slice by value like this but doesn't come from DB

o.QueryTable("Ticket").Filter("Status", "Pending").All(&newticket)

To create a sub-array from existing array based on value parameters like id , status and snapshot_id

I have reproduced your scenario and sliced the array based on value parameters

package main

import (
    "fmt"
)

type Ticket struct {
    id          int
    status      string
    snapshot_id int
}

func main() {

    var newTicket []Ticket

    TicketArr := []Ticket{{1, "available", 1}, {2, "n.a", 2}, {3, "available", 30}}

    for _, v := range TicketArr {

        if v.status == "available" {

            newTicket = append(newTicket, v)
        }
    }

    fmt.Println("newTicket", newTicket)

}

Output:

newTicket [{1 available 1} {3 available 30}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM