6

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.

1
  • It seems like result[item] should be an array correct? So you would need to map over that array as well. result[item][0].name should return the string. Commented Aug 14, 2018 at 12:39

3 Answers 3

13

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>
    )
Sign up to request clarification or add additional context in comments.

Comments

3

Try this code : Here is the link to the code on: https://codesandbox.io/s/pj1lv7y4xq

const arrayvals = [
   { Number: 1, newNumber: "1", name: "FB" },
    { Number: 3, newNumber: "2", name: "FB" },
     { Number: 7, newNumber: "5", name: "GK" },
      { Number: 8, newNumber: "4", name: "FW" }
]



function App() {
  return (
    <div className="App">
      <h1>Mapping object keys in react and returning child properties
</h1>
    {Object.entries(arrayvals).map((arr)=>{

        return <div>Number is : {arr[1].Number}  || NewNumber is : {arr[1].newNumber} ||  and Value is : {arr[1].name}</div>
    })}
    </div>
  );
}

Comments

2

You need to map again on the result using the key obtained as

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.