Skip to content

Commit

Permalink
📚 docs: update README.md #4
Browse files Browse the repository at this point in the history
  • Loading branch information
pnguyen215 committed Jan 14, 2025
1 parent b1c2fb0 commit 62e96bc
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -605,3 +605,33 @@ func main() {
}
}
```
### Loop through an object or array.
The `Foreach` method enables efficient iteration over objects or arrays. For objects, both the key and value are provided to the callback function, while for arrays, only the value is passed. The iteration can be halted by returning `false` from the callback.
eg.
```go
package main
import (
"fmt"
"github.com/sivaosorg/fj"
)
var json []byte = []byte(`{"user":{"id":"12345","name":{"firstName":"John","lastName":"Doe"},"email":"[email protected]","phone":"+1-555-555-5555","address":{"street":"123 Main St","city":"Anytown","state":"CA","postalCode":"12345","country":"USA"},"roles":[{"roleId":"1","roleName":"Admin","permissions":[{"permissionId":"101","permissionName":"View Reports","allowedActions":["view","download"]},{"permissionId":"102","permissionName":"Manage Users","allowedActions":["create","update","delete"]}]},{"roleId":"2","roleName":"Editor","permissions":[{"permissionId":"201","permissionName":"Edit Content","allowedActions":["create","edit","publish"]},{"permissionId":"202","permissionName":"View Analytics","allowedActions":["view"]}]}],"status":"active","createdAt":"2025-01-01T10:00:00Z","lastLogin":"2025-01-12T15:30:00Z"}}`)
func main() {
ctx := fj.GetBytes(json, "user.roles.#.permissions")
ctx.Foreach(func(key, value fj.Context) bool {
fmt.Println(value.String())
return true
})
}
// output:
// [{"permissionId":"101","permissionName":"View Reports","allowedActions":["view","download"]},{"permissionId":"102","permissionName":"Manage Users","allowedActions":["create","update","delete"]}]
// [{"permissionId":"201","permissionName":"Edit Content","allowedActions":["create","edit","publish"]},{"permissionId":"202","permissionName":"View Analytics","allowedActions":["view"]}]
```

0 comments on commit 62e96bc

Please sign in to comment.