Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through a nested json object array in the render (ReactJS)

Tags:

json

reactjs

I'm trying to iterate and display certain values of a JSON on my web application using ReactJS.

My render looks like this:

render() {

  const orders = 
  Object.keys(this.state.data).map((e,i) => {
   return (
     <div key = {i}>
       <div>ID: {this.state.data[e].id}</div>
       <div>Email: {this.state.data[e].email}</div>
       <div>Note: {this.state.data[e].note}</div>
       <div>{this.findValue(e)}</div>
     </div>
   )
 })

 return (
   <div>
     <div>
       {orders}
     </div>
   </div>
 );
}

Now everything looks fine until I run this.findValue where it immediately returns after the first iteration instead of returning multiple divs.

findValue = (e) => {
    for(let key2 in this.state.data[e].line_items) {    
        return (
          <div>
            Line item: {this.state.data[e].line_items[key2].title}
         </div>
        )
   }

How would I be able to return every line item? Thanks in advance.

like image 361
Matthew Werdean Avatar asked Apr 28 '26 06:04

Matthew Werdean


1 Answers

When you return something from the function given to map, you are just returning what the current element should be mapped to in the new array. When you return inside the for..in, you are returning from the findValue method instead.

You could use map on the array of keys in line_items as well.

findValue = e => {
  const { line_items } = this.state.data[e];
  return Object.keys(line_items).map(key => (
    <div key={key}>Line item: {line_items[key].title}</div>
  ));
};
like image 65
Tholle Avatar answered Apr 30 '26 22:04

Tholle