我在一个json文件中有一个对象数组:
[
{
"department": "Sound Department",
"subDepartments": [
"Supervising Sound Editor",
"Dialog Editor",
"Sound Designer",
"Foley Artis",
"Sound Recordist"
]
},
{
"department": "Camera Department",
"subDepartments": [
"Camera Operator",
"Second Assistant Camera",
"Other Assistant Camera",
"Steadycam Operator",
"Focus Puller"
]
},
{
"department": "Production Department",
"subDepartments": [
"Camera Operator",
"Second Assistant Camera",
"Other Assistant Camera",
"Steadycam Operator",
"Focus Puller"
]
}
]
从这里我创建了一个部门下拉菜单。从这里我想创建另一个子部门下拉菜单的基础上,哪个部门已被选中。
Departments的下拉菜单工作正常,也可以将该部门存储在一个状态中。我只是不知道如何过滤这些内容。
import React, { useState } from "react";
import "./CreateJobPage3.css"
import Button from "../Input/Button";
import Select from "../Input/Select";
import departmentData from "../Data/departmentSheet.json";
const CreateJobPage3 = (props) => {
const [department, setDepartment] = useState()
const [subDepartment, setSubDepartment] = useState()
const departments = departmentData.map((data) => data.department)
const subDepartments = departmentData.filter(item => {
return item.department === department;
});
const departmentHandler = (props) =>{
setDepartment(props)
}
const subDepartmentHandler = (props) =>{
setSubDepartment(props)
}
return (
<>
<div className="CJP3___inner">
<Select
placeholder="Choose Department"
options={departments}
value={department}
onChangeOption={departmentHandler}
/>
<Select
placeholder="Choose Department"
options={subDepartments}
value={subDepartment}
onChangeOption={subDepartmentHandler}
isMulti={true}
/>
</div>
<Button className="isGrey formButton" text={"Add Function"} />
</>
);
};
export default CreateJobPage3;
2条答案
按热度按时间kdfy810k1#
所以你已经有了过滤,你缺少的是从对象中获取
subDepartments
属性,为此你可以使用map
,但是因为你的subDepartments
本身是一个数组,我会使用flatMap
,否则结果会是[['sub1,'sub2']]
x4shl7ld2#
这里有两个问题。通过使用
Array.filter
,您的结果将是整个department对象的数组,而您只需要子部门。在这种情况下,使用Array.find,然后只访问subDepartments数组会快一点。