How to loop through object in JSX using React.js

不问归期 提交于 2019-12-05 02:04:52

Instead of $.each use map:

{AccountTypes.map(function(a) {
     return (
         <option key={a.id} val={a.id}>{a.name}</option>
     );
 })}

Points to note :

Your data is in an Object , not in an array : therefore to loop through it , you will have to use Object.keys(yourObject).map() instead of yourObject.map()

With this in mind ; here is the solution

var user = {
     fname:'John',
     lname : 'Doe',
     email:'test@test.com'
}

class App extends Component {
  render() {
    return (
      <p>
      <ul>
        {
          Object.keys(user).map((oneKey,i)=>{
            return (
                <li key={i}>{user[oneKey]}</li>
              )
          })
        }

      </ul>    
      </p>
    );
  }
}

You should use map to loop:

{AccountTypes.map((accountType) => 
  <option value={accountType.id}>{accountType.name}</option>)}

for rendering a list of children, you must add key attribute for each child so React will render them properly.Try this:

With JQuery map ( good for functional programming)

   {
        $.map(AccountTypes, function(type,index) {
            return <option key={type.id} val={type.id}>type.name</option>
        })
    }

With normal map :

{AccountTypes.map((type) => {
   return <option key={type.id} 
                  val={type.id}>
            {type.name}
          </option>
)}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!