oxy_js oxy_js -4 years ago 128
JSON Question

Iterate on json in react component

I have this json in my react component as

codeData


{
"type":"Simple count",
"codeCount": {
"lang": {
"java": 4,
"cpp":3,
"c":5
},
"ds": {
"array": 4,
"tree":5
}
}
}


In page I want to show above json in form of list as follows.

lang
*java(4)
*cpp(3)
*c(5)

ds
*array(4)
*tree(5)


For that I have to iterate through java object
codeData.codeCount
.But I am not able to figure out how to show key and value in loop.

class Showdata extends Component {

render() {
const {codeData} = this.props;
return (
<div>
for (let [key, value] of {codeData.codeCount}(myObj)) {
<ul>

</ul>

}


</div>
);
}

Answer Source

Check this:

let data = {
   "type":"Simple count",
   "codeCount": {
    "lang": {
      "java": 4,
      "cpp":3,
      "c":5
    },
    "ds": {
      "array": 4,
      "tree":5
    }
   }
  }
class Showdata extends React.Component {

  render() {
    const {codeCount} = data;
    return (
      <div>
        {Object.keys(codeCount).map(key=>{
            return <ul>
                    {key}
                    {
                        Object.keys(codeCount[key]).map(el=> <li>{el} : {codeCount[key][el]}</li>)
                    }
                   </ul>
        })}
      </div>
    );
  }
 }
 ReactDOM.render(<Showdata/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download