How to iterate nested objects and render inside js

2019-04-28 15:18发布

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

2条回答
来,给爷笑一个
2楼-- · 2019-04-28 16:06

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>
);
查看更多
Melony?
3楼-- · 2019-04-28 16:15

I've decided to create my own method, due to the clunkyness of this.

function each(obj, callback){
    return (Array.isArray(obj))? forArray(obj, callback):forObject(obj, callback);
}
function forArray(obj, callback){
    return obj.map(callback);
}
function forObject(obj, callback){
    return Object.keys(obj).map(callback);
}


class MyComponent extends React.Component {
    render () {    
        var options = this.props.options;
        return (            
            <div>                    
                {each(options, function(groupItem){ return (                        
                     each(groupItem, function(key){return ( 

This is much easier to read.

查看更多
登录 后发表回答