skip to Main Content

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


  1. You can use a simple set of array map & flat operations to flatten out the tree:

    const 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"
        }
      }]
    }]
    
    const flattenedObjects = gridItems
      .flatMap(item => item.fields)
      .flatMap(Object.entries)
    
    flattenedObjects
      .forEach(([key, value]) =>
        console.log(`key: ${key}, value.id: ${value.id}, value.value: ${value.value}`)
      )

    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.

    return (
        {flattenedObjects.map(([key, item]) => 
            <input type="hidden" key={key} name={item.id} value={item.value} />
        )}
    )
    
    Login or Signup to reply.
  2. You can first use Array#flatMap to get all the fields in a flat array, then map over that to create the elements.

    return gridItems.flatMap(o => o.fields.flatMap(Object.entries))
            .map(([k, fld]) => <input type="hidden" name={k} key={k} value={fld.value} />);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search