Answer the question
In order to leave comments, you need to log in
How to remove extra nodes when filtering Json?
Good day everyone! There is a similar json structure:
const json = [
{
"type": "node",
"title": "Title 1",
"nodes": [
{
"type": "unit",
"name": "Unit01",
}
]
},
{
"type": "node",
"title": "Title 2",
"nodes": [
{
"type": "node",
"title": "Title 3",
"nodes": [
{
"type": "unit",
"name": "Unit10",
},
{
"type": "unit",
"name": "Unit11",
},
{
"type": "unit",
"name": "Unit12",
}
]
},
{
"type": "node",
"title": "Title 4",
"nodes": [
{
"type": "unit",
"name": "Unit20",
}
]
}
]
}
];
export default json;
import React, { Component} from 'react';
import json from './data'
class Node extends React.Component {
constructor(props) {
super(props);
this.state = {
showUnits: false,
}
this.onClickHandle = this.onClickHandle.bind(this);
}
onClickHandle(event) {
event.stopPropagation();
this.setState({showUnits: !this.state.showUnits});
}
render() {
const {showUnits} = this.state;
return (
<div className="node" onClick={this.onClickHandle}>{this.props.node.title}
<ul className="node__title" >
{showUnits && this.props.node.nodes.map(node => {
if (node.type === "node") {
return <Node node={node} value={this.props.value}/>
} else {
if (node.name.includes(this.props.value))
return <Unit unit={node} value={this.props.value}/>
}
})}</ul>
</div>
)
}
}
class Unit extends React.Component {
render() {
return (
<li className="unit__name">{this.props.unit.name}</li>
)
}
}
class SearchField extends React.Component {
constructor(props) {
super(props);
this.handleOnChange = this.handleOnChange.bind(this);
this.state = {
searchValue: "",
}
}
handleOnChange(event) {
const {value} = event.target;
this.setState({searchValue: value})
}
render() {
return (
<React.Fragment>
<form className="search-form">
<input type="text" className="search-form__input" placeholder="Поиск"
onChange={this.handleOnChange}/>
</form>
{json.map(node => <Node node={node} value={this.state.searchValue}/>)}
</React.Fragment>
)
}
}
class App extends Component {
render() {
return (
<main>
<SearchField/>
</main>
);
}
}
export default App;
Answer the question
In order to leave comments, you need to log in
We make a method that will recursively bypass the data and discard elements whose name does not contain the search string and does not have nested elements (either did not exist initially, or they were discarded). And instead of the original data, we display the result of this method. Somehow so .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question