作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我必须创建一个嵌套的对象数组并将其推送到一个数组中。
我的代码片段在名为 recipes.js 的文件中包含一组食谱,如下所示:
const createRecipe = () => {
const id = uuidv4()
recipes.push({
id: id,
title: '',
body: '',
ingredients: []
})
saveRecipe()
return id
}
const createIngredients = (recipes, text) => {
recipes.ingredients.push({
id: uuidv4(),
text,
completed: false
})
saveIngredients()
}
最佳答案
正如@DarkSigma 指出的那样recipes
是一个数组,这是错误的来源。
为了建立在已经说过的基础上,这里有一些更多的细节:
recipes.push({
id: id,
title: '',
body: '',
ingredients: []
})
产生以下数据结构:
[{id: 1, title: '', body: '', ingredients: []}, {id: 2, title: '', body: '', ingredients: [] /* etc. */}]
所以对于
recipes
中的每个项目,
ingredients
是另一个项目列表。
ingredients
喜欢:
recipes.ingredients.push({
id: uuidv4(),
text,
completed: false
})
错误是
recipes.ingredients
因为
recipes
是一个数组,所以我们必须找到
recipe
匹配
ingredients
我们正在添加。
const createIngredients = (recipes, recipeId , text) => {
// Look up the recipe for the given id
const foundRecipeById = recipes.find(x => x.id === recipeId);
if (foundRecipeById) {
// Now add the ingredients to the found recipe
foundRecipeById.ingredients.push({
id: uuidv4(),
text,
completed: false
})
saveIngredients()
}
else {
// Do something intelligent if the recipe is not found
}
}
这样我们就可以查找/匹配
recipe
与
ingredients
关于javascript - 如何将嵌套的对象数组推送到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63958074/
我是一名优秀的程序员,十分优秀!