filter JSON result by attribute if the obj. attribute is true with React.js

398 views Asked by At

Im trying to retrieve and filter JSON data with React.js and maybe hooks but I cant come with any good way to do it. Just now I have my JSON data local, so it does not come from restAPI or similar (for now)... and what Im trying is to create a menu with buttons that when I click on them I get filtered data. I know... it should not be very difficut to do it (cause Im doing it already in a veeeery basic way for a conditional that show different icones depending on if certain attribute is true.) but anyway im struggling with it.

Here is my code:

import React, {setState, useState} from 'react';

export const ByCourse = () => {
const projects = window.projects.aaData;
console.log('window.projects = ', projects);

return (
<div className="section-component">
  <h2 className="mt-2 mb-4">By Course</h2>

  <ul className="nav nav-tabs">
    <li className="nav-item">
      <a className="nav-link active" href="#">
        All
      </a>
    </li>
    <li className="nav-item">
      <a className="nav-link" href="#">
        Favorite
      </a>
    </li>
    <li className="nav-item">
      <a className="nav-link" href="#">
        Recent
      </a>
    </li>
    <li className="nav-item">
      <a className="nav-link" href="#">
        Assigned
      </a>
    </li>
  </ul>


  <div className="container">

    {projects.map(project => {

      return(
        <div className="row">
          <div className="w-100">
            <div className="d-flex border mt-1 mb-1 p-3">
              <div className="col-1">
                {project.favorite ? <i className="fa fa-star"></i> : <i className="fa fa-star-o"></i>}
              </div>
              <div className="col-11">
                <div className="font-weight-bold"> {project.projectTitle}</div>
                <div className="font-weight-normal"> {project.ouName}</div>
              </div>
            </div>
          </div>
        </div>

      )})}

  </div>
</div>
);};

and my data looks like this:

 projects = {"aaData":
 [
 {
   "index":0,
   "projectTitle":"123",
   "userTitle":"VVS-teknik grund",
   "ouName":"fertest1",
   "orgUnitId":1022,
   "projectId":2014,
   "favorite":false,
   "recent":false,
   "userAssigned":false,
   "projectStatus":"ACTIVE",
   "viewLink":"http://xxxxxx
 },
 {
   "index":1,
   "projectTitle":"AAA",
   "userTitle":"AAA",
   "ouName":"fertest1",
   "orgUnitId":1022,
   "projectId":2002,
   "favorite":false,
   "recent":true,
   "userAssigned":false,
   "projectStatus":"ACTIVE",
   "viewLink":"http://xxxxxx
 },
 {
   "index":2,
   "projectTitle":"Activity with image and text",
   "userTitle":"asdas",
   "ouName":"ferfer AB",
   "orgUnitId":1004,
   "projectId":1892,
   "favorite":false,
   "recent":false,
   "userAssigned":true,
   "projectStatus":"NEW",
   "viewLink":"http://xxxxxx"
}]

I tried using a solution from here: Filtering JSON results in categories - React Hooks but I get a WEBPACK_1 ERROR and cant fix it...

Im also doing a very basic filtering here:

{project.favorite ? <i className="fa fa-star"></i> : <i className="fa fa-star-o"></i>}

and basically what Im looking for is:

if attribute "favorite" is true -> show results with attr favorite true else if attribute "recent" is true -> just show results with attribute recent == true Thank you very much in advance, any help will be very very welcome.

3

There are 3 answers

1
Dane Stevens On BEST ANSWER

Here's a working example using useState to set a filter:

https://codesandbox.io/s/crazy-turing-jd3ym?fontsize=14&hidenavigation=1&theme=dark

1
saidfurkandize On

First of all, the filtering or those functions is not about React.js. It's about JavaScript.

I will try go to be honest, i don't undestand anything about your problem. Could you please write only your problem?

Note: Don't mix the conditional keyword or something like that. If you write the problem clearly we will (i) will help you. Bonus: I refactor your code.

Here changes list: 1- I removed the unnecessary import 2- Seperate your code. Make component. 3- Indentation 4- Short condition (Fix for duplicate code)

import React from 'react';

const Project = data => (
  <div className="row">
    <div className="w-100">
      <div className="d-flex border mt-1 mb-1 p-3">
        <div className="col-1">
          <i className={data.favorite ? "fa fa-star" : "fa fa-star-o"} />
        </div>
        <div className="col-11">
          <div className="font-weight-bold"> {data.projectTitle}</div>
          <div className="font-weight-normal"> {data.ouName}</div>
        </div>
      </div>
    </div>
  </div>
);

export const ByCourse = () => {
  const projects = window.projects.aaData;
  console.log('window.projects = ', projects);

  return (
    <div className="section-component">
      <h2 className="mt-2 mb-4">By Course</h2>

      <ul className="nav nav-tabs">
        <li className="nav-item">
          <a className="nav-link active" href="#">
            All
          </a>
        </li>
        <li className="nav-item">
          <a className="nav-link" href="#">
            Favorite
          </a>
        </li>
        <li className="nav-item">
          <a className="nav-link" href="#">
            Recent
          </a>
        </li>
        <li className="nav-item">
          <a className="nav-link" href="#">
            Assigned
          </a>
        </li>
      </ul>

      <div className="container">
        {projects.map(project => <Project data={project} />)}
      </div>
    </div>
  );
};
2
Zain Ul Abideen On

I am assuming you want to show the objects where favorite OR recent: true,

1) A simple way to do this is:

let projects = {
  "aaData": [{
          "index": 0,
          "projectTitle": "123",
          "userTitle": "VVS-teknik grund",
          "ouName": "fertest1",
          "orgUnitId": 1022,
          "projectId": 2014,
          "favorite": true,
          "recent": false,
          "userAssigned": false,
          "projectStatus": "ACTIVE",
          "viewLink": "http://xxxxxx"
      },
      {
          "index": 1,
          "projectTitle": "AAA",
          "userTitle": "AAA",
          "ouName": "fertest1",
          "orgUnitId": 1022,
          "projectId": 2002,
          "favorite": false,
          "recent": true,
          "userAssigned": false,
          "projectStatus": "ACTIVE",
          "viewLink": "http://xxxxxx"
      },
      {
          "index": 2,
          "projectTitle": "Activity with image and text",
          "userTitle": "asdas",
          "ouName": "ferfer AB",
          "orgUnitId": 1004,
          "projectId": 1892,
          "favorite": false,
          "recent": false,
          "userAssigned": true,
          "projectStatus": "NEW",
          "viewLink": "http://xxxxxx"
      }
  ]
}

for (let iterator = 0; iterator < projects.aaData.length; iterator++) {
    if (projects.aaData[iterator].favorite || projects.aaData[iterator].recent) {
        console.log(projects.aaData[iterator])
    } else {
      continue;
    }
}

2) Other way to do this is:

let projects = {
      "aaData": [{
              "index": 0,
              "projectTitle": "123",
              "userTitle": "VVS-teknik grund",
              "ouName": "fertest1",
              "orgUnitId": 1022,
              "projectId": 2014,
              "favorite": true,
              "recent": false,
              "userAssigned": false,
              "projectStatus": "ACTIVE",
              "viewLink": "http://xxxxxx"
          },
          {
              "index": 1,
              "projectTitle": "AAA",
              "userTitle": "AAA",
              "ouName": "fertest1",
              "orgUnitId": 1022,
              "projectId": 2002,
              "favorite": false,
              "recent": true,
              "userAssigned": false,
              "projectStatus": "ACTIVE",
              "viewLink": "http://xxxxxx"
          },
          {
              "index": 2,
              "projectTitle": "Activity with image and text",
              "userTitle": "asdas",
              "ouName": "ferfer AB",
              "orgUnitId": 1004,
              "projectId": 1892,
              "favorite": false,
              "recent": false,
              "userAssigned": true,
              "projectStatus": "NEW",
              "viewLink": "http://xxxxxx"
          }
      ]
    }

  let filteredArrayWithNull = projects.aaData.filter((object) => {
    return object.favorite || object.recent ?
            object : null
  })

  let finalFilteredArray = filteredArrayWithNull.filter((object) => object!=null)

  console.log(finalFilteredArray);

To read more about filter(); here is a comprehensive guide