Search code examples
arraysreactjsobjectecmascript-6lodash

Mapping object keys in react and returning child properties


I have a report that maps the number of objects. In my example there is 3 object arrays. I want to get a value of one of the properties in each object when it maps.

Here is my snippet React code that returns the reports:

return (
    <React.Fragment>
        { Object.keys(result).map((item, i) => (
            <div key={i} className="report">
                    <h3>{result[item].name}</h3>
            </div>
    ))}
    </React.Fragment>
)

It maps const result that outputs like:

result = {GK: Array(1), FB: Array(2), FW: Array(1)}

There are 3 reports above - GK, FB and FW

I now want to go into each report and get a value. Lets look at FB:

FB: [ 0:{Number: 1, newNumber:"1", name: "FB" }
      1:{Number: 1, newNumber:"1", name: "FB" }
    ]

I want to make sure that when I retrieve the report the name property also maps and any other property I want to grab.

<h3>{result[item].name}</h3>

I thought the above would retrieve name. So the result I get is 3 blank reports.


Solution

  • Again map through the inner elements present in the result[item].

       return (
            <React.Fragment>
                { Object.keys(result).map((item, i) => (
                    <div key={i} className="report">
                           {result[item].map((media,ind) =>
                             <div key={ind}>{media.name}</div>
                          )}
                    </div>
            ))}
            </React.Fragment>
        )