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>
))}
>Solution :
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>
))}