英文:
can i make aloop inside a loop and both end at the same time?
问题
{formData.div.map((clsName, index) => (
<div className={clsName}>
<input type={formData.type[index]} />
</div>
))}
英文:
well i have a form data object
:
const formData = {
type: [
"text",
"text",
"number",
"email",
"text",
"text",
"text",
"number"],
div: [
"col-6",
"col-6",
"col-6",
"col-6",
"col-12",
"col-4",
"col-4",
"col-4",
],
};
i wanted to make 2 loops so the output be like this
<div className="col-6">
<input type="text"/>
</div>
<div className="col-6">
<input type="text"/>
</div>
.
.
.
I've tried a nasted loop but I already know that the inner loop will end in the first outer loop
{formData.div.map((clsName) => (
<div className={clsName}>
{formData.type.map((type) => (
<input type={type} />
))}
</div>
))}
答案1
得分: 4
以下是您要翻译的内容:
地图功能的第二个参数是数组中的索引,所以您可以使用该索引来提取相应的 type
条目,就像这样:
{formData.div.map((clsName, index) => (
<div className={clsName}>
<input type={formData.type[index]} />
</div>
))}
但是有一些潜在的问题,比如必须确保 type
和 div
数组的长度相同。
我建议您改变输入数据的形状,改为使用对象数组,而不是数组对象:
const formData = [
{
type: 'text',
div: 'col-6',
},
{
type: 'text',
div: 'col-6',
},
{
type: 'number',
div: 'col-6',
}
]
这将相关的信息保持在一起,并允许您更直观地进行映射:
{formData.map((entry) => (
<div className={entry.div}>
<input type={entry.type} />
</div>
))}
英文:
The second argument to the map function is the index within the array, so you could use that index to pull the corresponding type
entry, like this:
{formData.div.map((clsName, index) => (
<div className={clsName}>
<input type={formData.type[index]} />
</div>
))}
But there are a couple of potential problems, like having to be sure the type
and div
arrays are the same length.
I'd recommend that you instead change the shape of your input data to be an array of objects, instead of an object of arrays:
const formData = [
{
type: 'text',
div: 'col-6',
},
{
type: 'text',
div: 'col-6',
},
{
type: 'number',
div: 'col-6',
}
]
This keeps the related info together and allows you to map over it much more intuitively:
{formData.map((entry) => (
<div className={entry.div}>
<input type={entry.type} />
</div>
))}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论