In my React app, I have an array defined as below;
gridItems = [
{
"fields": [{
"fNameField-0": {
"id": "fNameField",
"value": "Row1 Col1"
},
"lNameField-0": {
"id": "lNameField",
"value": "Row1 Col2"
}
}]
}, {
"fields": [{
"fNameField-1": {
"id": "fNameField",
"value": "Row2 Col1"
},
"lNameField-1": {
"id": "lNameField",
"value": "Row2 Col2"
}
}]
}
]
I want to iterate over this array and create hidden "input" elements for each nested object. So basically, I want to dynamically create the below element
<input type="hidden" name={fld.id} value={fld.value} />
and in this case, there should be 4 input elements corresponding to each of the nested object.
2
Answers
You can use a simple set of array map & flat operations to flatten out the tree:
To render out to JSX, we can simply map the resulting values.
You can use the output in a simple map call to achieve that.
You can first use
Array#flatMap
to get all the fields in a flat array, thenmap
over that to create the elements.