javascript - 如何循环遍历对象数组中的数组

标签 javascript arrays loops object reactjs

我知道如何在 react 中运行循环,但我如何在一个已经在循环数组中的对象中执行它?

我试图将每个成分项目显示为 <li> , 到目前为止,我已经使用了配方,但我迷失了配料。如果有人可以插话,我将不胜感激。

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

最佳答案

这样怎么样:

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

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

还有一点,你不应该使用数组的索引作为,因为以后编辑数组时会很难管理。如果您为 key 分配一些非常独特的东西,比如 idindex + Date.now()

会更好

关于javascript - 如何循环遍历对象数组中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39714080/

相关文章:

javascript - 仅使用 CSS 和 javascript 将 div 的隐藏部分移动到 View 中

javascript - 检查 Javascript 数组中是否存在属性值为 'x' 的对象

C:二维数组与普通数组相同大小的区别

java - 无限循环,因为迭代器不动

r - 简单线性回归模型的迭代

javascript - 允许用户更改 div 中的文本

javascript - 无法使用 D3 使路径绘制缓慢增长

javascript - 如何设置 window.opener() 函数的宽度和高度?

javascript - JQuery InArray 无法正常工作?

python - 高级 for 循环