Home > database >  How to filter and map array within array in React
How to filter and map array within array in React

Time:12-08

How to search/filter arrays within arrays in React? For example:

I have this data (videosData.js):

[
    {
        "id": 1,
        "title": "Video 1",
        "video_leght": "00:50:00",
        "date": "20.05.2010",
        "questions": [
            {
                "id": 1,
                "question": "Question 1 ",
                "url": "Link"
              },
              {
                "id": 2,
                "question": "Question 2",
                "url": "Link"
              },
              {
                "id": 3,
                "question": "Question 3",
                "url": "Link"
              }         
        ]
    },
    {
        "id": 2,
        "title": "Video 2",
        "video_leght": "01:00:00",
        "date": "14.07.2016",
        "questions":[
            {
                "id": 1,
                "question": "Question 1 ",
                "url": "Link"
              },
              {
                "id": 2,
                "question": "Question 2",
                "url": "Link"
              },
              {
                "id": 3,
                "question": "Question 3",
                "url": "Link"
              }        
        ]
    }
]

This is my complete code:

import React, { useState } from "react";
import Style from "./SearchResults.module.css";
import DataList from "../data/videosData";

function SearchResults() {
  const [search, setSearch] = useState("");

  return (
    <div className={Style.Body}>
      <div className={Style.Search_div}>
        <input
          className={Style.Textbox1}
          onChange={(e) => setSearch(e.target.value)}
        ></input>
        <button className={Style.Btn_Potrazi}>Trazi</button>
      </div>

      <div>
      {DataList.filter((item) => {
            return search.toLowerCase() === ""
              ? ""
              : item.title.toLowerCase().includes(search);
          })
          .map((item) => (
            <h2>{item.title}</h2>
          ))}
      </div>
    </div>
  );
}

export default SearchResults;

I managed to filter the "title" in the array but what I really need is filter out only the questions. So when typing in the search box a word it would filter and show only that question that contains that word...

I'm completely newbie to web development, I watched lots of YouTube videos but just couldn't find a tutorial with an explanation in own words on how to solve this problem.

Thanks in advance!

CodePudding user response:

I would go with a memo for this as below.

const filteredQuestions = useMemo(()=>{
  var filteredQues =[]
  vv.forEach((p,index) => {
    p.questions.forEach((eachQues, _i)=>{
        if(search==='' || eachQues.question.toLowerCase().includes(search.toLowerCase())){
            filteredQues.push(eachQues);
        }
      })
    
    });
    return filteredQues
},[search]);

Then use filteredQuestions in the render to render filtered questions. I can also convert the above one to a memoized react component and use that directly.

Note: I haven't added conditional checks here.

CodePudding user response:

const questionFilter = [
    {
        "id": 1,
        "title": "Video 1",
        "video_leght": "00:50:00",
        "date": "20.05.2010",
        "questions": [
            {
                "id": 1,
                "question": "Question 1 ",
                "url": "Link"
              },
              {
                "id": 2,
                "question": "Question 2",
                "url": "Link"
              },
              {
                "id": 3,
                "question": "Question 3",
                "url": "Link"
              }         
        ]
    },
    {
        "id": 2,
        "title": "Video 2",
        "video_leght": "01:00:00",
        "date": "14.07.2016",
        "questions":[
            {
                "id": 1,
                "question": "Question 1 ",
                "url": "Link"
              },
              {
                "id": 2,
                "question": "Question 2",
                "url": "Link"
              },
              {
                "id": 3,
                "question": "Question 3",
                "url": "Link"
              }        
        ]
    }
]

const result = questionFilter.map(item => 
    item.questions.filter(qitem => qitem.question.includes('Question 1'))
)

console.log(result)

Here's how it done.

  • Related