js_248
js_248

Reputation: 2122

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

Upvotes: 1

Views: 425

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104529

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'/>

Upvotes: 3

Related Questions