0

There is JSON called by fetch() request looks like this:

[{
"Info": "",
"Val": "3"
},
{
"Info": "",
"Val": "5"
},
{
"Info": "",
"Val": "1"
},
{
"Info": "",
"Val": "1"
}]

My purpose is to filter data according a filed called Val.

 library = library.filter(item =>
             item.Val==FilterVal
 )

Let me make an example to explain what I want to do. Look at this input :<input value={this.state.FilterVal} onChange={this.handlerFilter} />

FilterVal is going to be a number for example 1 or some numbers separated by comma 1,5,4 . For example user types 1 on input ,the result must return the objects that Valis 1. For the next time type 1,5,4must return me the objects that Val are 1 and 5 and 4.

Here is a piece of my code:

  class App extends React.Component {
   constructor(props) {
    super(props);
    this.state = {
        data: [],
        library: null,
        FilterVal: "",

    }
}
componentDidMount() {
        fetch('/json.bc', {
            method: 'POST',
        })
            .then(response => response.text())
            .then(text => {
                const Maindata = JSON.parse(text.replace(/\'/g, '"'))
                 this.setState(state => ({
                    ...state,
                    data: Maindata
                }), () => {
                    this.reorganiseLibrary()
                })
            }).catch(error => console.error(error))
    })
}
reorganiseLibrary = () => {
    const { FilterVal} = this.state;
    let library = data;
    if (FilterVal !== "") {
        library = library.filter(item =>
             item.Val==FilterVal
        )
    }
    library = _.chunk(library);
    this.setState({
        library
    })

}

handlerFilter = evt =>
    this.setState(
        {
            FilterVal: evt.target.value
        },
        () => {
            this.reorganiseLibrary();
        }
    )
renderLibrary = () => {
const { library} = this.state;
    if (!library || (library && library.length === 0)) {
        return <div>nodata</div>
    }
return library.map((item, i) => (
        <div>
                  <span>{item.name}</span>
                  <span>{item.Val}</span>
       </div>
    ))
}

render() {
    const { library} = this.state;
    return (
        <div>
         {this.renderLibrary()}
         <input value={this.state.FilterVal} onChange={this.handlerFilter} />
      </div>
    )
}
}
ReactDOM.render(<App />, document.getElementById('Result')) 
2
  • 1
    Sorry but what is the question? Is your code not working? What's the current error or behavior? Commented Jun 13, 2019 at 9:46
  • Hi @ keul. Main problem is how to filter data based on {this.state.FilterVal}. For example FilterVal = 1 so result is objects of JSON that field Val for them is 1,but I want when FilterVal =1,2 result will include objects of JSON that field Val for them are 1 and 2.Does it make sense? Commented Jun 13, 2019 at 9:53

2 Answers 2

1

Just adjust your filter:

const values = FilterVal.split(',').map(v => Number(v))
library = library.filter(item => values.includes(item.Val))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, but it does not work correctly.For example FilterVal is 2,3,4,5,. The result is 1 3 2 4 4 Firstly there is not 1 in FilterVal so why it is in result and next for getting objects of Val=5, FilterVal should contain another number after 5,
0

You can use FilterVal.includes(item.Val). This is working solution.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      library: null,
      FilterVal: ""
    };
  }
  componentDidMount() {
    var originalArray = [
      {
        Info: "",
        Val: "3"
      },
      {
        Info: "",
        Val: "3"
      },
      {
        Info: "",
        Val: "2"
      },
      {
        Info: "",
        Val: "4"
      },
      {
        Info: "",
        Val: "4"
      },
      {
        Info: "",
        Val: "5"
      },
      {
        Info: "",
        Val: "2"
      },
      {
        Info: "",
        Val: "1"
      }
    ];
    this.setState({ data: originalArray });
  }
  reorganiseLibrary = () => {
    let FilterVal = this.state.FilterVal;
    let library = this.state.data;
    if (FilterVal !== "") {
      FilterVal = FilterVal.split("");
      library = library.filter(item => {
        if (FilterVal.includes(item.Val)) return item;
      });
    } else {
      library = null;
    }
    // library = _.chunk(library);
    this.setState({
      library
    });
  };

  handlerFilter = evt =>
    this.setState(
      {
        FilterVal: evt.target.value
      },
      () => {
        this.reorganiseLibrary();
      }
    );
  renderLibrary = () => {
    const { library } = this.state;
    if (!library || (library && library.length === 0)) {
      return <div>nodata</div>;
    }
    return library.map((item, i) => (
      <div>
        <span>{item.name}</span>
        <span>{item.Val}</span>
      </div>
    ));
  };

  render() {
    const { library } = this.state;
    return (
      <div>
        {this.renderLibrary()}
        <input value={this.state.FilterVal} onChange={this.handlerFilter} />
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("Result"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='Result' />

3 Comments

I have a question.Can we split FilterVal based on , because when I want to use this filter for something else not just a number it wont work correctly
For example I want to use FilterVal to filter data based on Info field of JSON and Info can be something like this :B.B or even a text such as test text by space.
var originalArray = [ { Info: "Accommodation only", Val: "3" }, { Info: "B.B", Val: "3" }, { Info: "B.B", Val: "4" }, { Info: "R.O", Val: "4" }, { Info: "R.O", Val: "5" }, { Info: "B.B", Val: "2" }, { Info: "Accommodation only", Val: "1" } ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.