theJuls
theJuls

Reputation: 7470

Rendering a object onto a React component

I thought this would be a simple task, but I've been working on this all day but still can't seem to figure it out.

I am receiving a very large (multiple layers of objects) JSON file which I stored in a state of my component, now I need to render that data on the screen. This has become difficult, because within the object I have several others objects which also may contain other objects.

So far, I am using Object.keys(myJSONObject).map(...) to try to get it done, however I can't seem to find a way to reach all the 'sub-objects'. Here is my current code:

render: function(){
       return (

        <div>

            {
                Object.keys(_this.state.content).map(function (key) {
                     if (typeof _this.state.content[key] instanceof Object){
                  //go through all objects and sub-objects???

                        }
                    return <div > Key: {
                        key
                    }, Value: {
                                _this.state.content[key]

                    } </div>;
                })
            }


        </div>
    );
   }

Edit: I should probably add that my object is _this.state.content

Edit 2: Here is an example of the object I am looking to iterate through. Keep in mind that is it a lot bigger than this.

{ "3.8": [ "Something something" ], 
 "3.2": [ { "Blabla": [ "More things I am saying", "Blablablabal", "Whatever" ] } ],
 "2.9": [ { "Foo": [ "bar", "something something something something", "blablablabalbalbal" ] } ]} 

Edit 3: Here is how I would somewhat like it to look when rendered:

3.8:
 - Something something
3.2:
 - Blabla:
     - More things I am saying
     - Blablablabal
     - Whatever
2.9:
 -Foo:
     -bar
   ...

Upvotes: 1

Views: 428

Answers (2)

Piotr Berebecki
Piotr Berebecki

Reputation: 7468

Is this what your are after: http://codepen.io/PiotrBerebecki/pen/PGjVxW

The solution relies on using React's reusable components. It accepts objects of varying levels of nesting as per your example. You can adjust it further to accommodate even more types of objects.

const stateObject = {
  "3.8": [ "Something something" ], 
  "3.2": [ { "Blabla": [ "More things I am saying", "Blablablabal", "Whatever" ] } ],
  "2.9": [ { "Foo": [ "bar", "something something something something", "blablablabalbalbal" ] } ]
} 


class App extends React.Component {
  render() { 
    const renderMainKeys = Object.keys(stateObject)
      .map(mainKey => <MainKey mainKey={mainKey} 
                      innerObject={stateObject[mainKey]} />);   

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


class MainKey extends React.Component {
  render() {
    if (typeof this.props.innerObject[0] === 'string') {
      return (
        <div>
          <h4>{this.props.mainKey}</h4>
          <ul>
            <li>{this.props.innerObject[0]}</li>
          </ul>
        </div>
      );
    }

    const innerObjectKey = Object.keys(this.props.innerObject[0])[0];
    const innerList = this.props.innerObject[0][innerObjectKey];

    return (
      <div key={this.props.mainKey}>
        <h4>{this.props.mainKey}</h4>
        <InnerKey innerObjectKey={innerObjectKey} innerList={innerList}/>
      </div>
    )
  }
}

class InnerKey extends React.Component {  
  render() {
    return (
      <ul>
        <li>{this.props.innerObjectKey}</li>
        <InnerList innerList={this.props.innerList} />
      </ul>
    )
  }
}


class InnerList extends React.Component {   
  render() {
    if (!Array.isArray(this.props.innerList)) {
      return (
        <ul>
          <li>{this.props.innerList}</li>
        </ul>
      );
    }

    const listItems = this.props.innerList.map(function(item, index) {
      return <li key={index}>{item}</li>;
    });

    return (
      <ul>
        {listItems}
      </ul>
    );
  }
}


ReactDOM.render(
  <App />,
  document.getElementById('app')
);

Upvotes: 1

Harkirat Saluja
Harkirat Saluja

Reputation: 8124

Here is a code which I wrote sometime back to handle 3 layers of nesting in my json file.

JSON

var a = {
    "parent":{
       "name":"x",
       "child":{
          "name":"y",
          "subchild":{
                "name":"check"
          }
       }
  }
}

Iterator

  Object.keys(obj).map(function(key,index){
    let section = obj[key]
    //getting subsections for a single section
    let subSections = section["subsections"] // get you nested object here
    Object.keys(subSections).map(function(subSectionId,key){
      //getting a single sub section
        let subSection=subSections[subSectionId]
      //getting instruments for a sub section
      let  nestedSection = subSection["//key"] //get you next nested object here

         Object.keys(instruments).map(function(instrumentId,key){
                    //operation
                 }
             })
         })
    })
  })

Hope it helps.

Upvotes: 1

Related Questions