'Showing sub array data acccording to main array ID

This is my Array Which is in the separate JSON file

{
        "Women": [
            {
                "id"  : 1,
                "name"  : "See All",
                "children" : [""]
            },
            {
                "id"  : 2,
                "name"  : "Clothes",
                "children" : [ "Coats & jackets" , "Suits & blazers" , "Skirts"]
            },
            {
                "id"  : 3,
                "name"  : "Shoes",
                "children" : [ "Boots" , "Flats" , "Ankle boots"]
            },
            {
                "id"  : 4,
                "name"  : "Bags",
                "children" : [ "Handbags" , "Backpacks" , "Clutches"]
            },
            {
                "id"  : 5,
                "name"  : "Accessories",
                "children" : [ "Jewelry" , "Belts" , "Scarves & Shawls"]
            },
            {
                "id"  : 6,
                "name"  : "Beauty",
                "children" : [ "Make Up" , "Face Care" , "Hand Care"]
            }
        ],
        "Men": [
            {
                "id"  : 1,
                "name"  : "See All",
                "children" : [""]
            },
            {
                "id"  : 2,
                "name"  : "Clothes",
                "children" : [ "Men" , "B" , "C"]
            },
            {
                "id"  : 3,
                "name"  : "Shoes",
                "children" : [ "D" , "E" , "F"]
            },
            {
                "id"  : 4,
                "name"  : "Bags",
                "children" : [ "E" , "F" , "G"]
            },
            {
                "id"  : 5,
                "name"  : "Accessories",
                "children" : [ "H" , "I" , "J"]
            },
            {
                "id"  : 6,
                "name"  : "Beauty",
                "children" : [ "K" , "L" , "M "]
            }
        ],
        "Kids": [
            {
                "id"  : 1,
                "name"  : "See All",
                "children" : [""]
            },
            {
                "id"  : 2,
                "name"  : "Clothes",
                "children" : [ "Kid" , "B" , "C"]
            },
            {
                "id"  : 3,
                "name"  : "Shoes",
                "children" : [ "D" , "E" , "F"]
            },
            {
                "id"  : 4,
                "name"  : "Bags",
                "children" : [ "E" , "F" , "G"]
            },
            {
                "id"  : 5,
                "name"  : "Accessories",
                "children" : [ "H" , "I" , "J"]
            },
            {
                "id"  : 6,
                "name"  : "Beauty",
                "children" : [ "K" , "L" , "M "]
            }
        ]
    }

This is how the array has called into a js file

import { useState, Fragment } from 'react'
import { Tab, Listbox, Transition } from '@headlessui/react'
import { CheckIcon, SelectorIcon } from '@heroicons/react/solid'
import SubCategoryComponent from './SubCategoryComponent';
import * as Icons2 from "../../../assets/svg/icon";

import AdminCatData from  './CategoriesDataAdmin.json';

function classNames(...classes) {
  return classes.filter(Boolean).join(' ')
}

const mainCategories = [
  { id: 1, icon: <Icons2.seeall /> },
  { id: 2, icon: <Icons2.frock01 /> },
  { id: 3, icon: <Icons2.shoes06 /> },
  { id: 4, icon: <Icons2.purse01 /> },
  { id: 5, icon: <Icons2.bag05 /> },
  { id: 6, icon: <Icons2.hat02 /> },
  { id: 7, icon: <Icons2.shirt1 /> },
  { id: 8, icon: <Icons2.shoes1 /> },
  { id: 9, icon: <Icons2.bag05 /> },
  { id: 10, icon: <Icons2.purse02 /> },
  { id: 11, icon: <Icons2.hat /> },
  { id: 12, icon: <Icons2.shoes05 /> },
  { id: 13, icon: <Icons2.bag05 /> },
  { id: 14, icon: <Icons2.bow /> },
  { id: 15, icon: <Icons2.hat03 /> }
]

const Women = AdminCatData.Women.map ((data) => {
    
  return(
    { 
      ...data,
    }
  )
  }
)

const Men = AdminCatData.Men.map ((data) => {
    
  return(
    { 
      ...data,
    }
  )
  }
)


const Kids = AdminCatData.Kids.map ((data) => {
    
  return(
    { 
      ...data,
    }
  )
  }
)

const Categories = () => {

  const [pTitle, setPTitle] = useState('');
  const [pCategory, setPCategory] = useState('')
  const [pSubCategory, setPContent] = useState('');
  const [showPopUp, setshowPopUp] = useState(false)
  const [addCategory, setAddCategory] = useState('')

  const [subCatIndex, setsubCatIndex] = useState(1)


  const [selectedMainCategory, setSelectedMainCategory] = useState(mainCategories[3])

  let [categories] = useState({

  })






  const updateTitle = (productTitle) => {
    setPTitle(productTitle);
  }

  const onDeleteClick = (categoryID, categoryIndex) => {
    // delete method here

    if(categoryIndex == 0){
      console.log(categories.Women[categoryID-1]);
    }
    else if(categoryIndex == 1){
      console.log(categories.Men[categoryID-1]);
    }
    else{
      console.log(categories.Kids[categoryID-1]);
    }
  }

  return (
    <div className="w-full sm:px-0">
      <Tab.Group>
        <Tab.List className="flex p-1 space-x-1 bg-red-300 rounded-xl">
          {(["Women", "Men", "Kids"]).map((category) => (
            <Tab
              key={category}
              className={({ selected }) => 
                classNames(
                  'w-full py-2.5 text-sm leading-5 font-medium text-black rounded-lg', 
                  'focus:outline-none focus:ring-2 ring-offset-2 ring-offset-red-400 ring-white ring-opacity-60', 
                  selected ? 'bg-white shadow' : 'text-white hover:bg-white/[0.12] hover:text-white'
                )
              }
            >
              {category}
            </Tab>
          ))}
        </Tab.List>

        <Tab.Panels className="mt-2 flex p-1 space-x-1 bg-red-300 rounded-xl">

{/*Women Tab*/}
            <Tab.Panel
              className={({ selected }) =>
              classNames(
                'w-full py-2.5 text-sm leading-5 font-medium text-black rounded-lg', 
                'focus:outline-none focus:ring-2 ring-offset-2 ring-offset-red-400 ring-white ring-opacity-60', 
                selected ? 'bg-white shadow' : 'text-white hover:bg-white/[0.12] hover:text-white'
              )
            }
            >

            <div className='grid grid-cols-3'>
              <ul className='col-span-1 mr-4'>
                {Women.map((item, index) => (
                  <ul key={item.id} onClick={() => setsubCatIndex(item.id)}>
                    <li className="relative p-3 rounded-md hover:bg-coolGray-100">
                      <h3 className="text-sm font-medium leading-5">
                        {item.name}
                      </h3>

                    <ul className="flex mt-1 space-x-1 text-xs font-normal leading-4 text-coolGray-500">
                      <li>Sub Categories </li>
                      <li>{item.children.join(' ')}</li>
                    </ul>

                    <a
                      href="#"
                      className={classNames(
                        'absolute inset-0 rounded-md',
                        'focus:z-10 focus:outline-none focus:ring-2 ring-red-400'
                      )}
                    />
                  </li>
                
                  </ul>
                ))}
                <button type="button" 
                        class=" content-center 
                                text-white bg-red-400 
                                hover:bg-red-300 font-medium 
                                rounded-none text-sm px-5 py-2.5 
                                text-center mr-2 mb-2 dark:bg-red-400 
                                dark:hover:bg-red-400"
                        onClick={() => setshowPopUp(true)}
                > Add new Category
                </button>
                </ul>

                <ul className='col-span-2 mr-4'>
                {Women.map((data) => (
                  <ul>
                    <li className="relative p-3 rounded-md hover:bg-coolGray-100">

                    <ul className="flex mt-1 space-x-1 text-xs font-normal leading-4 text-coolGray-500">
                      <li>Sub Categories </li>
                      <li>{data.children.join(' ')}</li>
                    </ul>

                    <a
                      href="#"
                      className={classNames(
                        'absolute inset-0 rounded-md',
                        'focus:z-10 focus:outline-none focus:ring-2 ring-red-400'
                      )}
                    />
                  </li>
                
                  </ul>
                ))}
                <button type="button" 
                        class=" content-center 
                                text-white bg-red-400 
                                hover:bg-red-300 font-medium 
                                rounded-none text-sm px-5 py-2.5 
                                text-center mr-2 mb-2 dark:bg-red-400 
                                dark:hover:bg-red-400"
                        onClick={() => setshowPopUp(true)}
                > Add new Subcategory
                </button>
                </ul>

              </div>

            </Tab.Panel>
{/* End Women Tab */}



        </Tab.Panels>
      </Tab.Group>

      {showPopUp ? (
        <>
          <div
            className="justify-center items-center flex overflow-x-hidden overflow-y-auto fixed inset-0 z-50 outline-none focus:outline-none"
          >
            <div className="relative w-auto my-6 mx-auto max-w-3xl">
              {/*content*/}
              <div className="border-0 rounded-lg shadow-lg relative flex flex-col w-full bg-white outline-none focus:outline-none">
                {/*header*/}
                <div className="flex items-start justify-between p-5 border-b border-solid border-blueGray-200 rounded-t">
                  <h3 className="text-3xl font-semibold">
                    Select one category
                  </h3>
                  <button
                    className="p-1 ml-auto bg-transparent border-0 text-black opacity-5 float-right text-3xl leading-none font-semibold outline-none focus:outline-none"
                    onClick={() => setshowPopUp(false)}
                  >
                    <span className="bg-transparent text-black opacity-5 h-6 w-6 text-2xl block outline-none focus:outline-none">
                      x
                    </span>
                  </button>
                </div>
                {/*body*/}
                <div className="relative p-6 flex-auto">
                  <p className = "text-lg mb-2">Add new category</p>
                  <input type = "text" placeholder = 'Add here' className = 'w-full rounded-lg border-gray-300 shadow-md active:ring-red-400 focus:ring-red-400'/>
                  
                  <p className = "text-lg mt-3">Select an icon</p>
{/** Icon Slector */}
                  <div>
                    <Listbox value={selectedMainCategory} onChange={setSelectedMainCategory}>
                      {({open}) => (<>
                        <Listbox.Label
                            className="block text-sm font-medium text-gray-700">
                              Icon
                        </Listbox.Label>

                          <div className="mt-1 relative">
                            <Listbox.Button
                              className="bg-white relative w-full border border-gray-300 rounded-md shadow-sm pl-3 pr-10 py-2 text-left cursor-default focus:outline-none focus:ring-1 focus:ring-red-500 focus:border-red-500 sm:text-sm">
                                <span className="block truncate">
                                  {selectedMainCategory.icon}
                                </span>
                                <span
                                  className="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none">
                                  <SelectorIcon className="h-5 w-5 text-gray-400" aria-hidden="true"/>
                                </span>
                            </Listbox.Button>

                            <Transition
                                show={open}
                                as={Fragment}
                                leave="transition ease-in duration-100"
                                leaveFrom="opacity-100"
                                leaveTo="opacity-0"
                                >
                                  <Listbox.Options
                                    className=" absolute z-10 mt-1 w-full 
                                                bg-white shadow-lg max-h-60 
                                                rounded-md py-1 text-base ring-1 
                                                ring-black ring-opacity-5 
                                                overflow-auto focus:outline-none 
                                                sm:text-sm">
                                      {mainCategories.map((mainCategory) => (<Listbox.Option
                                            key={mainCategory.id}
                                            className={({active}) => classNames(active ? 'text-white bg-red-600' : 'text-gray-900', 'cursor-default select-none relative py-2 pl-3 pr-9')}
                                            value={mainCategory}
                                            >
                                            {({selected, active}) => (<>
                                              <span
                                                className={classNames(selected ? 'font-semibold' : 'font-normal', 'block truncate')}>
                                                  {mainCategory.icon}
                                                  </span>
                                                    {selected ? (<span
                                                      className={classNames(active ? 'text-white' : 'text-red-600', 'absolute inset-y-0 right-0 flex items-center pr-4')}
                                                    >
                                                    <CheckIcon className="h-5 w-5"
                                                      aria-hidden="true"/>
                                                      </span>) : null}
                                              </>)}
                                      </Listbox.Option>))}
                                  </Listbox.Options>
                            </Transition>
                            </div>
                        </>)}
                    </Listbox>
                  </div>
{/** End Icon Slector */}
                </div>
                {/*footer*/}
                <div className="flex items-center justify-end p-6 border-t border-solid border-blueGray-200 rounded-b">
                  <button
                    className="text-red-500 background-transparent font-bold uppercase px-6 py-2 text-sm outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150"
                    type="button"
                    onClick={() => setshowPopUp(false)}
                  >
                    Close
                  </button>
                  <button
                    className="bg-red-400 text-white active:bg-emerald-600 font-bold uppercase text-sm px-6 py-3 rounded shadow hover:shadow-lg outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150"
                    type="button"
                    onClick={() => setshowPopUp(false)}
                  >
                    Save Changes
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div className="opacity-25 fixed inset-0 z-40 bg-black"></div>
        </>
      ) : null
      }
    </div>
  )
}
export default Categories;

What I need to do is, add an onClick event (onClick event for array showing place text area.) to the main array and take its id, and according to that id I want to show its children.

As an example :

if the main array id is 2 it means the second array component which has clothes, Then I need to show its children "Coats & jackets", "Suits & blazers", "Skirts",

can you suggest me a solution for that ???

How Currently Shows the output (All the children data displayed.) enter image description here

This is What I need (Only the selected Item Children are displayed. This is an edited picture for your understanding)

enter image description here



Solution 1:[1]

As per I understood your question I think you can use this piece of code I'd Assumed that you'd converted your JSON to array

function findChildren(id) {
  const item = array.find((elem) => elem.id === id);

  if (item) {
    return item.children.length
      ? item.children.join(",")
      : "no product in this category";
  } else {
    return `Product doesnt exists with id ${id}`;
  }
}

console.log(findChildren(1));

If you want to inject this in a DOM just replace the return "string" with your render function

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abbas Shaikh