1

I am displaying data from a json in my application, but I need to display only the data where the field always is true, in this case, I need just show the 7 and 8. How can I do this?

This is my JSON example with the field true and null:

  {
     "id": 6,
     "title": "Some title",
     "content": "Some content",
     "always": null
  },
  {
     "id": 7,
     "title": "Some title",
     "content": "Some content",
     "always": true
  },
  {
     "id": 8,
     "title": "Some title",
     "content": "Some content",
     "always": true
  }

And I'm using this to fetch, but this code shows all the items

  componentDidMount = async () => {
    const parseJSON = (resp) => (resp.json ? resp.json() : resp)

    const checkStatus = (resp) => {
      if (resp.status >= 200 && resp.status < 300) {
        return resp
      }
      return parseJSON
    }
    const headers = {
      'Content-Type': 'application/json'
    }

    try {
      const data = await fetch('http://myurl/api', {
        method: 'GET',
        headers
      }).then(checkStatus)
        .then(parseJSON)
      this.setState({ data })
    } catch (error) {
      this.setState({ error })
    }
  }

render() {
  const { data } = this.state;

  return(
      <ul>
        {data.map(test =>
           <li key={test.id}>
             <h2>{test.title}</h2>
              <p>{test.content}</p>
           </li>
              )}
      </ul>
  )
}
CodeG
  • 417
  • 2
  • 6
  • 15

3 Answers3

3

Its better to have a filter before you map

{data.filter(x => x.always).map(test => (
  <li key={test.id}>
    <h2>{test.title}</h2>
    <p>{test.content}</p>
  </li>
)}
Chris
  • 6,331
  • 1
  • 21
  • 25
Guruparan Giritharan
  • 15,660
  • 4
  • 27
  • 50
0

Filter it to show the item having "always":true

function App() {
  let items = [
    {
    "id": 6,
    "title": "Some title",
    "content": "Some content",
    "always": null
 },
 {
    "id": 7,
    "title": "Some title",
    "content": "Some content",
    "always": true
 },
 {
    "id": 8,
    "title": "Some title",
    "content": "Some content",
    "always": true
 }]
 let filtered = items.filter(item=>item.always===true);
  return (
    <ul>
     {filtered.map(test=>
       <li key={test.id}>
         <h2>{test.id}.{test.title}</h2>
          <p>{test.content}</p>
       </li>
      )}
    </ul>
  );
}
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
0

Use filter before the map.

     { items.filter(({always}) => always).map(({id, title, content})=>
           <li key={id}>
             <h2>{title}</h2>
              <p>{content}</p>
           </li>) }
Sarun UK
  • 6,210
  • 7
  • 23
  • 48