Filter accepts a function that returns a boolean. The function is ran over the object elements. If the function returns true, the element passes the filter and is added to the new object of filtered elements. If false, the value is skipped (or in other words filtered out). After iterating through al
(fn func(key string, value *Value) bool)
| 454 | // }) |
| 455 | // filteredObject.IsEqual(map[string]interface{}{"qux":"quux"}) //succeeds |
| 456 | func (o *Object) Filter(fn func(key string, value *Value) bool) *Object { |
| 457 | opChain := o.chain.enter("Filter()") |
| 458 | defer opChain.leave() |
| 459 | |
| 460 | if opChain.failed() { |
| 461 | return newObject(opChain, nil) |
| 462 | } |
| 463 | |
| 464 | if fn == nil { |
| 465 | opChain.fail(AssertionFailure{ |
| 466 | Type: AssertUsage, |
| 467 | Errors: []error{ |
| 468 | errors.New("unexpected nil function argument"), |
| 469 | }, |
| 470 | }) |
| 471 | return newObject(opChain, nil) |
| 472 | } |
| 473 | |
| 474 | filteredObject := map[string]interface{}{} |
| 475 | |
| 476 | for _, kv := range o.sortedKV() { |
| 477 | func() { |
| 478 | valueChain := opChain.replace("Filter[%q]", kv.key) |
| 479 | defer valueChain.leave() |
| 480 | |
| 481 | valueChain.setRoot() |
| 482 | valueChain.setSeverity(SeverityLog) |
| 483 | |
| 484 | if fn(kv.key, newValue(valueChain, kv.val)) && !valueChain.treeFailed() { |
| 485 | filteredObject[kv.key] = kv.val |
| 486 | } |
| 487 | }() |
| 488 | } |
| 489 | |
| 490 | return newObject(opChain, filteredObject) |
| 491 | } |
| 492 | |
| 493 | // Transform runs the passed function on all the elements in the Object |
| 494 | // and returns a new object without effecting original object. |