gpt4 book ai didi

javascript - 如何将嵌套的对象数组推送到数组?

转载 作者:行者123 更新时间:2023-12-04 08:53:44 25 4
gpt4 key购买 nike

我必须创建一个嵌套的对象数组并将其推送到一个数组中。
我的代码片段在名为 recipes.js 的文件中包含一组食谱,如下所示:

const createRecipe = () => {
const id = uuidv4()

recipes.push({
id: id,
title: '',
body: '',
ingredients: []
})
saveRecipe()

return id
}

然后,在文件成分.js 中,我导入了函数 createRecipe() 并尝试将成分推送到配方数组,如下所示:

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
}
}
这样我们就可以查找/匹配 recipeingredients

关于javascript - 如何将嵌套的对象数组推送到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63958074/

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