Andrea
Andrea

Reputation: 5

Filter out null and empty values from JSON array in react

How can I add an if statement or filter out null and empty values in my code? I need to remove/ not show the name value that is null or empty.

componentDidMount() {
    fetch('https://url')
        .then(res => res.json())
        .then((data) => {
            data.sort(function (y,x){
                return y.listId - x.listId;
          })
          data.sort();
          this.setState({ items: data })
          console.log(this.state.items)
     })
     .catch(console.table)
  }

  return (
      <div className="list-container">
          <h1>My List</h1>
          {this.state.items.map((item) => (
              <div className="list">
          )}

Here's an example of my json array:

[
    {"id": 755, "listId": 2, "name": ""},
    {"id": 203, "listId": 2, "name": ""},
    {"id": 684, "listId": 1, "name": "Item 684"},
    {"id": 276, "listId": 1, "name": "Item 276"},
    {"id": 736, "listId": 3, "name": null},
    {"id": 926, "listId": 4, "name": null}
]

Upvotes: 0

Views: 2517

Answers (3)

pbrune
pbrune

Reputation: 500

You can filter the array by doing this:

const items = this.state.items.filter(item => item.name !== '' && item.name !== null);

This will return a new array that doesn't have items with a blank or null name.

Edit for comment:

You can add this in your code like this:

componentDidMount() {
    fetch('https://url')
    .then(res => res.json())
    .then((data) => {
      const filteredData = data.filter(item => item.name !== '' && item.name !== null);
      filteredData.sort(function (y,x){
        return y.listId - x.listId;
      })
      filteredData.sort();
      this.setState({ items: filteredData })
      console.log(this.state.items)
    })
    .catch(console.table)
}

Upvotes: 0

Shyam
Shyam

Reputation: 5497

let data = [
{"id": 755, "listId": 2, "name": ""},
{"id": 203, "listId": 2, "name": ""},
{"id": 684, "listId": 1, "name": "Item 684"},
{"id": 276, "listId": 1, "name": "Item 276"},
{"id": 736, "listId": 3, "name": null},
{"id": 926, "listId": 4, "name": null}] 

console.log(data.filter(({name}) => name))

Upvotes: 0

You can use the filter array method in this way:

data.filter(d => d !== "" && d !== null)

Add this line before the sorting function like this:

componentDidMount() {
    fetch('https://url')
    .then(res => res.json())
    .then((data) => {
      const filteredData = data.filter(d => d !== "" && d !== null)
      filteredData.sort(function (y,x){
        return y.listId - x.listId;
      })
      filteredData.sort();
      this.setState({ items: filteredData })
      console.log(this.state.items)
    })
    .catch(console.table)
}

Also (probably unrelated), why are you sorting two times?

Upvotes: 1

Related Questions