Search through object properties recursively with a complex filter. Inspired by jscodeshift find method. It was created to help in testing react components with Jest and react-test-renderer, but can be used anywhere.
There are two main functions:
Return array properties of object that match the filter.
Return first property of object that match the filter.
-
Object - object to recursively search through.
-
Filter - object that defines structure (keys and values) to search. If property of object has all keys that filter has (property can also contain other keys) and this keys has the same values, the property will be returned as matched.
In case if filter key is Array (see children in examples). Value of object property should have all items that filter value has.
Main reason for creating this package was to help with react testing. React-test-renderer renders React components to pure JavaScript objects. And if we need to simulate click on button we should find this button in component tree.
import {findFirst} from 'object-deep-search'
...
const component = renderer.create(<TestComponent/>)
const tree = component.toJSON()
//define filter
const filter = {
type: 'button',
props: {
className: 'my-button-classname',
children: ['Submit']
}
}
//Simulate button onClick method
findFirst(tree, filter).props.onClick()