我正在从 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
中只有一个对象且有 1 个 key
,即 Brand
,那么您应该使用 .find()
而不是 filter()
来获取 该对象的 values
,然后您可以对其进行映射:
const brandProperties = useMemo(
() => carProperties?.find(property => property.key === "Brand"),
[carProperties]
);
然后在你的 JSX 中,你可以映射
brandProperties.values
:
brandProperties?.values.map(brand =>
<Div key={brand.id}>
<Form.Check>
<Form.Check.Input
type="radio"
id={brand.id.toString()}
value={brand.name}
/>
<Form.Check.Label className="form-check-label">{brand.name}</Form.Check.Label>
</Form.Check>
</Div>
)