How to iterate nested objects and render inside jsx?

柔情痞子 提交于 2019-12-05 07:22:13

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>
);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!