1
{this.props.datacat.forEach(function (key,value) {

  Object.keys(key).forEach(function(key2,value2) {
       console.log("yes");
       if(key2 == 'name'){
           return <Option value="zzz" key="bbb">fff</Option>;

       }
   })
})}  

//data of this.props.datacat

[
  {
    "4967": "Others.",
    "4968": "Sports & Beachwear > Others.",
    "4969": "Lingerie & Nightwear > Others.",
    "4971": "Pants & Shorts > Others.",
    "name": "Women Clothes"
  },
  {
    "4798": "Supplements > Others.",
    "4802": "Men's Grooming > Others.",
    "4952": "Others.",
    "4953": "Medical Supplies > Others.",
    "4954": "Personal Pleasure > Others.",
    "4955": "Personal Care > Others.",
    "4956": "Pedicure & Manicure > Others.",
    "6647": "Lips > Lip Tint"
    "name": "Health & Beauty"
  }
]

I'm beginner of reactjs, I have some data and want to loop through it and render to select box value. In the above code I tried to loop the data and render to select box option value. It successfully prints yes in console log but the html does not render as expected. Anyone has faced such an issue before? Please help :(.

UI

console log

Dhaval Jardosh
  • 7,151
  • 5
  • 27
  • 69
catch me
  • 41
  • 5

2 Answers2

3

forEach method only loops over items. i urge you to try .map array helper method.

To make this work with .forEach, create empty array and push in your Option component.

then return your empty array

1

Firstly use map to render items, Second, you will also need to return whatever returns from the object as well, as it's a double loop that we need to traverse through.

const data = [
  {
    "4967": "Others.",
    "4968": "Sports & Beachwear > Others.",
    "4969": "Lingerie & Nightwear > Others.",
    "4971": "Pants & Shorts > Others.",
    name: "Women Clothes"
  },
  {
    "4798": "Supplements > Others.",
    "4802": "Men's Grooming > Others.",
    "4952": "Others.",
    "4953": "Medical Supplies > Others.",
    "4954": "Personal Pleasure > Others.",
    "4955": "Personal Care > Others.",
    "4956": "Pedicure & Manicure > Others.",
    "6647": "Lips > Lip Tint",
    name: "Health & Beauty"
  }
];

class App extends React.Component {
  render() {
    return data.map(singleData=>{
     return Object.keys(singleData).map(key=>{
       if(key==='name'){
         return <div>{singleData[key]}</div>
       }
     })
    })
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Dhaval Jardosh
  • 7,151
  • 5
  • 27
  • 69