首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据主数组ID显示子数组数据

根据主数组ID显示子数组数据
EN

Stack Overflow用户
提问于 2022-03-21 06:18:17
回答 1查看 51关注 0票数 0

,这是我的数组,它位于单独的JSON文件中

代码语言:javascript
复制
{
        "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 "]
            }
        ]
    }

数组是如何调用js文件

代码语言:javascript
复制
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;

我需要做的是添加一个onClick事件(onClick事件用于数组显示place区域)。到主数组并接受它的id,根据这个id,我想显示它的子数组.

例如:

如果主数组id是2,它指的是第二个有衣服的数组组件,那么我需要给它的孩子看“外套和夹克”、“西装和夹克”、“裙子”,

,你能给我一个解决办法吗?

当前如何显示输出(显示的所有子数据。)

--这是我所需要的(只显示选定的项子。这是一张编辑好的图片,供您理解)

EN

回答 1

Stack Overflow用户

发布于 2022-03-21 06:36:18

根据我理解您的问题,我认为您可以使用这段代码,我假设您已经将JSON转换为数组

代码语言:javascript
复制
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));

如果您想将其插入DOM --仅用替换--使用呈现函数替换返回"string"

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71553476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档