很确定我错过了一些简单的东西,但这段代码让我很头疼。
我在本地 json
文件中有一个 array
{
"type": [
{
"name": "Accommodation",
"icon": "🏨",
"subcategory": [
"Hotels",
"Motels",
"Bed & Breakfasts"
]
},
{
"name": "Guided Tours",
"icon": "🚌",
"subcategory": [
"Audio & Self Guided",
"Cruises, Sailing & Water",
"Food, Wine & Nightlife"
]
}
]
}
并导入到 React 组件中
import { type } from './assets/json/company-type.json';
然后我对 companyType
的 name
使用 filter
(它基于 select
值住宿
或导游
。在映射
之前映射返回的项目后,子类别
<ul>
{type
.filter(item => {
return item.name === companyType;
})
.map(item => {
item.subcategory.map(subcategory => {
<li key={subcategory}>
<label id={subcategory} htmlFor={subcategory}>
<input
type="radio"
name={subcategory}
value={subcategory}
/>
<span />
{subcategory}
</label>
</li>;
});
})}
</ul>
但是,没有返回任何内容。然而,如果我 log
subcategory
我会在控制台中返回每个内容。我错过了什么?
最佳答案
这是因为您没有从 .map() 方法返回。 使用此修改后的代码,它将按预期工作
<ul>
{type
.filter(item => {
return item.name === "Accommodation";
})
.map(item => {
return item.subcategory.map(subcategory => {
return (
<li key={subcategory}>
<label id={subcategory} htmlFor={subcategory}>
<input
type="radio"
name={subcategory}
value={subcategory}
/>
<span />
{subcategory}
</label>
</li>
);
});
})}
</ul>
codeSandbox 链接:https://codesandbox.io/s/4881483j7x
关于javascript - 过滤数组,然后将数组映射到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52790390/