0

I want to implement a search in a Treeview which renders a list of nested Data. I am using Material UI to add the UI code for this and need to add a function which can search through the nested JSON objects and return the parsed nested JSON only.

My Data -

const TreeViewData = {
  id: 'root',
  name: 'Documents',
  children: [
    {
      id: '1',
      name: 'Report',
      children: [
        {
          id: '2',
          name: 'PDF',
        },
      ],
    },
    {
      id: '3',
      name: 'Files',
      children: [
        {
          id: '4',
          name: 'Excel',
        },
      ],
    },
    {
      id: '5',
      name: 'Programs',
      children: [
        {
          id: '6',
          name: 'Codes',
        },
        {
          id: '7',
          name: 'Data',
        },
      ],
    },
  ],
};

I need to add a function like onSearch(text) so that when user inputs any search text he will see the reduced tree view with parsed data.

For example -

onSearch(R) should return

const TreeViewData = {
  id: 'root',
  name: 'Documents',
  children: [
    {
      id: '1',
      name: 'Report',
      children: [
        {
          id: '2',
          name: 'PDF',
        },
      ],
    },
    {
      id: '5',
      name: 'Programs',
      children: [
        {
          id: '6',
          name: 'Codes',
        },
        {
          id: '7',
          name: 'Data',
        },
      ],
    },
  ],
};

again onSearch(excel) returns

const TreeViewData = {
  id: 'root',
  name: 'Documents',
  children: [
    {
      id: '3',
      name: 'Files',
      children: [
        {
          id: '4',
          name: 'Excel',
        },
      ],
    },
  ],
};

Note - Tried with Lodash too but that didn't helped.

swetansh kumar
  • 475
  • 7
  • 17

1 Answers1

0

You could search into the tree structure by using recursion. There is a similar question here

Angel González
  • 150
  • 1
  • 4