2

I have a json file like this

{"id": 1,
   "categoryName": "Download",
   "children": [
      {  "id": 3,
         "name": "name",
         "text": "text"
      }
   ]
}

and I have input for search. I can search onChange categoryname like this but I want search children names. How can I do this?

    const [searchTerm, setSearchTerm] = useState("");
    const [searchResults, setSearchResults] = useState([]);
    const handleChange = event => {
        setSearchTerm(event.target.value);
    };

    useEffect(() => {
        const results = data.filter(item =>
            item.categoryName.toLowerCase().includes(searchTerm)
        );
        setSearchResults(results);

    }, [searchTerm]);

1 Answer 1

2

Currently You filtering by category name in line:

   item.categoryName.toLowerCase().includes(searchTerm)

You need to filter not by categoryName (case sensitive here) and focus on children.name like this:

   item.children[0].name.toLowerCase().includes(searchTerm)

But this solutions will work only if children array have one object.

For including every objects - You need to iterate thought this array.

let results = [];

for (let i = 0; i < data.children.length; i++) {
   oneChild = data.filter(item =>
       item.children[i].name.toLowerCase().includes(searchTerm)
   )
   results.push(oneChild)
}

After experimenting in sandbox - ii got this function, which filter in subelements of element, which are 2 nested levels

const results = data.map((element) => {
  return {
    ...element,
    subElements: element.children.filter((subElement) =>
      subElement.name.includes(searchTerm)
    )
  };
});

And finally that solution should filter:

  useEffect(() => {
    let filteredArray = data
      .filter((element) =>
        element.children.some((subElement) =>
          subElement.name.includes(searchTerm)
        )
      )
      .map((element) => {
        let newElt = Object.assign({}, element); // copies element
        newElt.subElements = newElt.children.filter((subElement) =>
          subElement.name.includes(searchTerm)
        );
        return newElt;
      });

    setSearchResults(filteredArray);
  }, [searchTerm]);
Sign up to request clarification or add additional context in comments.

9 Comments

I tried but it didn't work, it's an element of array. Am I missing something?
Can You try with that - item.children[0].name.toLowerCase().includes(searchTerm) and also reproduce code in sandbox?
Thanks :) Here is the sandbox codesandbox.io/s/lingering-microservice-s8h5s
@okh let's check the last useEffect at edited question
Sorry, no errors but it doesn't work right :(
|

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.