abrahamlinkedin abrahamlinkedin - 13 days ago 9
JSON Question

reactjs running for loop with json data

I have a hypothetical JSON file that reads like so:

{
"main": [
{ "dish": "steak",
"side": [
{"platter": "yogurt"},
{"platter": "popcorn"}
]
},
{ "dish": "fish",
"side": [
{"platter": "salad"}
]
}
]
}


I am currently having problems understanding how to run a for loop on this data with ReactJS. The rest of my code is organised as follows:

getInitialState:function(){
return {fulldata: {main:[{side:[]}]}}
},

componentDidMount:function(){
var self = this;
$.getJSON('https://yooarel.fakewebsite', function(resultes){
self.setState({fulldata: resultes});
});
},

rundmc:function(){
return (<ul>
{this.state.fulldata.main.map(function(m, i){
return m.side.map(function(make, o){
return <li key={o}>{make.platter}</li>
})
})}
</ul>)
},
render:function(){
var self = this;
return (<div>
<ul>
{this.state.fulldata.main.map(function(m, i){
<li key={i}>
<span>{m.dish}</span>
{self.rundmc()}
</li>
})}
</ul>
</div>)
}


I am attempting to place a
<ul li>
block that lists out the different types of
dishes
I have. And then, for each dish under my
li
block, I am also attempting to place a
ul li
block that lists out the different
platter
under each dish. This is what I am trying to accomplish under my
rundmc()
function.

My code, as is, shows all platters under both of my
ul ul li
blocks. I am not sure how to output only the appropriate
platter
for each
dish
.

Answer

You are iterating all the data in rundmc function as well, you have to pass the current dish as a parameter and iterate only the side array

rundmc:function(dish){
  return (<ul>
      {
        dish.side.map(function(make, o){
          return <li key={o}>{make.platter}</li>
        })
      }
    </ul>)
},
render:function(){
  var self = this;
  return (<div>
    <ul>
      {this.state.fulldata.main.map(function(m, i){
        <li key={i}>
          <span>{m.dish}</span>
          {self.rundmc(m)}
        </li>
      })}
    </ul>
  </div>)
}