gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:44:05 26 4
gpt4 key购买 nike

我知道如何在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com