我正在从 API 获取以下格式的数据:
const carProperties = [
{
"key": "Brand",
"values": [
{
"id": 1,
"name": "Ford"
},
{
"id": 2,
"name": "Chevy"
},
{
"id": 3,
"name": "Honda",
}
]
},
{
"key": "Color",
"values": [
{
"id": 100,
"name": "Blue"
},
{
"id": 200,
"name": "Red"
},
{
"id": 300,
"name": "White",
}
]
}
]
我需要按其过滤这些数据key
,然后将其映射values
到单选按钮、复选框等 HTML 元素。我似乎无法获得正确的语法来映射这些值。这是我所拥有的:
carProperties?.filter(property => property.key === "Brand").map((data, index) => (
<Div key={index}>
<Form.Check>
<Form.Check.Input
type="radio"
id={data.values.id.toString()}
value={data.values.name}
/>
<Form.Check.Label className="form-check-label">{data.values.name}</Form.Check.Label>
</Form.Check>
</Div>))
的类型carProperties
有:
export interface CarProperty {
key: string,
values: CarPropertyValue[]
}
export interface CarPropertyValue {
id: number,
name: string,
}
您需要映射值,而不是
carProperties
数组的过滤版本。有几种方法可以做到这一点,但如果您可以保证您的对象中只有一个对象carProperties
具有key
ofBrand
,那么您应该使用.find()
而不是filter()
。一旦找到品牌属性,这将停止对数组的搜索,并返回您正在查找的对象,然后您可以访问该对象.values
上的属性,然后您可以映射该对象:该
useMemo()
钩子将有助于避免每次组件重新渲染时都研究对象的数组Brand
,而只会在安装时或carProperties
更改时搜索一次。然后在你的 JSX 中,你可以brandProperties.values
像这样映射:如果您可以在
carProperties
其中拥有多个具有Brand
键的对象,那么您可以使用嵌套映射将values
每个对象的数组映射到您的Div
: