Answer the question
In order to leave comments, you need to log in
How to filter an array of objects by matching the search string with any property?
There is an object:
const searchtest = [
{ id: "01", name: "Text1" },
{ id: "02", name: "Text12" },
{ id: "03", name: "Text123" },
{ id: "04", name: "Text1234" },
{ id: "05", name: "Text12345" },
{ id: "06", name: "Text123456" },
{ id: "07", name: "Text1234567" },
{ id: "09", name: "Text12345678" },
{ id: "10", name: "Text12345678910" }
];
onChange = e => {
this.setState({ search: e.target.value });
};
get searchtest() {
const search = this.state.search.toLowerCase().trim();
return parseInt(search) >= 0 ? searchtest.filter(({ id }) => id.toLowerCase().indexOf(search) > -1) : searchtest.filter(({ name }) => name.toLowerCase().indexOf(search) > -1);
}
<div>
<input
value={this.state.search}
onChange={this.onChange}
placeholder="Введи id или name"
/>
<div>
{this.searchtest.map((kef, i, a) => (
<div>
<div key={kef.name} data-id={kef.name}>
name: {kef.name}
</div>
<div key={kef.id} data-id={kef.id}>
id: {kef.id}
</div>
</div>
))}
</div>
</div>
const searchtest = [
{ id: "01", name: "Text1", number: "111" },
{ id: "02", name: "Text12", number: "222" },
{ id: "03", name: "Text123", number: "333" },
{ id: "04", name: "Text1234", number: "444" },
{ id: "05", name: "Text12345", number: "555" },
{ id: "06", name: "Text123456", number: "666" },
{ id: "07", name: "Text1234567", number: "777" },
{ id: "08", name: "Text1234567", number: "888" },
{ id: "09", name: "Text12345678", number: "999" },
{ id: "10", name: "Text12345678910", number: "101010" }
];
Answer the question
In order to leave comments, you need to log in
get searchtest() {
const search = this.state.search.toLowerCase().trim();
return search
? searchtest.filter(n => Object.values(n).some(m => m.toLowerCase().includes(search)))
: searchtest;
}
{this.searchtest.map((kef, i, a) => (
<div style={style}>
<div key={kef.name} data-id={kef.name}>
name: {kef.name}
</div>
<div key={kef.id} data-id={kef.id}>
id: {kef.id}
</div>
</div>
))}
{this.searchtest.map(n => (
<div key={n.id}>
<div>name: {n.name}</div>
<div>id: {n.id}</div>
</div>
))}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question