I want to create a search filter for my data array.it has multiple objects and keys like this one,
[
{
"fname": "Jayne",
"lname": "Washington",
"email": "[email protected]",
"gender": "female"
},
{
"fname": "Peterson",
"lname": "Dalton",
"email": "[email protected]",
"gender": "male"
},
{
"fname": "Velazquez",
"lname": "Calderon",
"email": "[email protected]",
"gender": "male"
},
{
"fname": "Norman",
"lname": "Reed",
"email": "[email protected]",
"gender": "male"
}
]
I want search filter search anywhere on this array. ex: when I type input box I want to search anywhere inside an object. like fname,lname,email,gender
how can i do it? please help me
If I want to restrict the search for only first and last names how to do that?
To find an object in an array in React: Call the find() method on the array, passing it a function. The function should return an equality check on the relevant property. The find() method returns the first value in the array that satisfies the condition.
You can keep a value filter
in your component state and use that to see if it is contained as a substring in any of the array element properties.
Example
class App extends React.Component {
state = {
filter: "",
data: [
{
fname: "Jayne",
lname: "Washington",
email: "[email protected]",
gender: "female"
},
{
fname: "Peterson",
lname: "Dalton",
email: "[email protected]",
gender: "male"
},
{
fname: "Velazquez",
lname: "Calderon",
email: "[email protected]",
gender: "male"
},
{
fname: "Norman",
lname: "Reed",
email: "[email protected]",
gender: "male"
}
]
};
handleChange = event => {
this.setState({ filter: event.target.value });
};
render() {
const { filter, data } = this.state;
const lowercasedFilter = filter.toLowerCase();
const filteredData = data.filter(item => {
return Object.keys(item).some(key =>
item[key].toLowerCase().includes(lowercasedFilter)
);
});
return (
<div>
<input value={filter} onChange={this.handleChange} />
{filteredData.map(item => (
<div key={item.email}>
<div>
{item.fname} {item.lname} - {item.gender} - {item.email}
</div>
</div>
))}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With