Malekaii
Malekaii

Reputation: 29

How do I loop through an array in an array of objects

I know how to run loops inside react but how do I do it inside an object which is already inside an array being looped?

I am trying to display each ingredient item as an <li>, so far I have got it working with recipe but I am lost with ingredient. If anyone could chime in, I'd appreciate it.

var Recipes = React.createClass({
// hook up data model
  getInitialState: function() {
    return {
      recipeList: [
        {recipe: 'Cookies', ingredients: ['Flour ', 'Chocolate']},
        {recipe: 'Cake', ingredients: ['Flour ', 'Sprinkles']},
        {recipe: 'Onion Pie', ingredients: ['Onion ', 'Pie-Crust']}
      ]
    }
  },

  loop: function() {
    {this.state.recipeList.flatMap('ingredients').map(item, index) => (
      <li key={index} className="list-group-item">{ingredient.ingredients}</li>
    )}
  },

  render: function() {
    return (
      <div>
        {this.state.recipeList.map((item, index) => (
          <div className="panel panel-default">
            <div className="panel-heading"><h3 className="panel-title">{item.recipe}</h3></div>
            <div className="panel-body">
              <ul className="list-group">
              {this.loop}
              </ul>
            </div>
          </div>
          )
        )}
      </div>
    );
  }
});

Upvotes: 1

Views: 180

Answers (2)

Phi Nguyen
Phi Nguyen

Reputation: 3056

How about this way :

  loop: function(ingredients) {
   return ingredients.map((ingredient, index) => {
    return (<li key={index} className="list-group-item">{ingredient}</li>)
   })
  },

  render(){
      ...
        {this.loop(item.ingredients)}
      ...
  }

One more thing, you shouldn't use index of array as key because it will be difficult to manage when editting the array later. It will be better if you assign key with something very unique like id or index + Date.now()

Upvotes: 3

Maciek Jurczyk
Maciek Jurczyk

Reputation: 575

You seem to be missing a return statement in the loop method.

You can cascade rendering as deep as you'd wish, only remember that you need to call the method instead of just placing it in the component structure (see this.loop without call parentheses in your sample):

var myComponent = React.createClass({
  renderListElements: function (parent) {
    return this.state.listElements[parent].map((element, index) => (
      <li 
        className="my-component__sub-component__list-element" 
        key={`${parent.uid}_${element.uid}`}
      >
        {element.name}
      </li>
    ));
  },

  render: function () {
    var parentsId = [ 0, 1, 2, 3 ];

    return (
      <div className="my-component">
        {parentsId.map((item, index) => (
          <div 
            className="my-component__sub-component" 
            key={item.uid}
          >
            {this.renderListElements(item)}
          </div>
        )}
      <div/>
    );
  }
});

Upvotes: 1

Related Questions