Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate nested objects and render inside jsx?

How can I render a nested map inside my jsx component?

I need to do the equivalent of a javascript for(key in groupItem){} See below.

class MyComponent extends React.Component {
    render () {    
        var options = this.props.options;
        return (            
            <div>
                {options.map(function(groupItem, key){ return (
                    /* 
                      Unexpected Token if using groupItem.map?
                      {groupItem.map(function(){return })}

                   */
                )})}
            </div>
        )
    }
}
Dropdown.defaultProps = {
   options:[{ 
      'groupX':{
          'apple':'lovely green apple',
          'orange':'juicy orange',
          'banana':'fat banana'
      }
   }]
}

JSON.stringify(groupItems) === {
    'groupX':{
        'apple':'lovely green apple',
        'orange':'juicy orange',
        'banana':'fat banana'
     }
}

WHY DON'T THESE WORK?

groupItem.map - DOESN'T WORK

Object.keys(groupItem).forEach(function (key){ - DOESN'T WORK

like image 489
Steve Tomlin Avatar asked Jun 27 '16 14:06

Steve Tomlin


1 Answers

You were almost right with your Object.keys implementation, (map is a property for arrays only), but the syntax error is coming from the wrapping {}. You don't need to escape, you're already inside js syntax.

return (            
    <div>
        {options.map(function(groupItem, key){ return (
            Object.keys(groupItem).map(function(item){return (
                <YourComponent group={groupItem} item={item} />
            );})
        );})}
    </div>
);
like image 78
weisk Avatar answered Sep 30 '22 09:09

weisk