删除嵌套在对象内部的数组项

Remove an array item nested inside of an object

我正在尝试根据数组中的 title 属性从对象数组中删除特定项目。我将 运行 设置为可以查看数组项的问题,但我无法根据在删除函数中输入的参数将项从数组中拼接出来。我只是从函数中的 else 语句中返回错误消息。

我试过使用 find, forEach, findIndex 并匹配大小写,以测试根据索引或 key 'text' 的文本值删除结果。在论坛推荐中搜索答案之前,我将我尝试过的所有功能都注释掉了。我所有的食谱函数都在工作,还有我的 createIngredient 函数,它向食谱数组添加了一个对象。但是 removeIngredient 函数我一直试图开始工作,并不是因为上面提到的问题。

let recipes = []

// Read existing recipes from localStorage
const loadRecipes = () => {
    const recipesJSON = localStorage.getItem('recipes')

    try {
        return recipesJSON ? JSON.parse(recipesJSON) : []
    } catch (e) {
        return []
    } 
}

// Expose recipes from module
const getRecipes = () => recipes

const createRecipe = () => {
    const id = uuidv4()
    const timestamp = moment().valueOf()

    recipes.push({
        id: id,
        title: '',
        body: '',
        createdAt: timestamp,
        updatedAt: timestamp,
        ingredient: []
    })
    saveRecipes()

    return id
}

// Save the recipes to localStorage
const saveRecipes = () => {
    localStorage.setItem('recipes', JSON.stringify(recipes))
}

// Remove a recipe from the list
const removeRecipe = (id) => {
    const recipeIndex = recipes.findIndex((recipe) => recipe.id === id)

    if (recipeIndex > -1) {
        recipes.splice(recipeIndex, 1)
        saveRecipes()
    }
}

// Remove all recipes from the recipe array
const cleanSlate = () => {
    recipes = []
    saveRecipes()
}

const updateRecipe = (id, updates) => {
    const recipe = recipes.find((recipe) => recipe.id === id)

    if (!recipe) {
        return
    }

    if (typeof updates.title === 'string') {
        recipe.title = updates.title
        recipe.updatedAt = moment().valueOf()
    }

    if (typeof updates.body === 'string') {
        recipe.body = updates.body
        recipe.updateAt = moment().valueOf()
    }

    saveRecipes()
    return recipe
}

const createIngredient = (id, text) => {
    const recipe = recipes.find((recipe) => recipe.id === id)

    const newItem = {
        text,
        have: false
    }
    recipe.ingredient.push(newItem)
    saveRecipes()
}

const removeIngredient = (id) => {
    const ingredient = recipes.find((recipe) => recipe.id === id)
    console.log(ingredient)
    const allIngredients = ingredient.todo.forEach((ingredient) => console.log(ingredient.text))

    // const recipeIndex = recipes.find((recipe) => recipe.id === id)

    // for (let text of recipeIndex) {
    //     console.log(recipdeIndex[text])
    // }

// Attempt 3
    // if (indexOfIngredient === 0) {
    //     ingredientIndex.splice(index, 1)
    //     saveRecipes()
    // } else {
    //     console.log('error')
    // }
    // Attempt 2
    // const recipe = recipes.find((recipe) => recipe.id === id)
    // const ingredients = recipe.todo 
    // // let newItem = ingredients.forEach((item) => item)

    // if (ingredients.text === 'breadcrumbs') {
    //     ingredients.splice(ingredients, 1)
    //     saveRecipes()
    // }
    // Attempt 1
    // const ingredientName = ingredients.forEach((ingredient, index, array) => console.log(ingredient, index, array))
    // console.log(ingredientName)

    // const recipeIndex = recipes.findIndex((recipe) => recipe.id === id)

    // if (recipeIndex > -1) {
    //     recipes.splice(recipeIndex, 1)
    //     saveRecipes()
    // }
}

recipes = loadRecipes()

输出

{id: "ef88e013-9510-4b0e-927f-b9a8fc623450", title: "Spaghetti", body: "", createdAt: 1546878594784, updatedAt: 1546878608896, …}
recipes.js:94 breadcrumbs
recipes.js:94 noodles
recipes.js:94 marinara
recipes.js:94 meat
recipes.js:94 ground beef
recipes.js:94 milk

所以我能够查看上面打印的输出并看到 ingredients 数组中的每个项目,但是尝试根据 index 数字或 [=19= 拼接项目] 不适用于我已经尝试过的函数以及我在 Whosebug 上找到的关于对象、数组和拼接方法的信息。

如果我理解正确(在阅读代码中注释掉的尝试后),您正试图从与传递给 id 相对应的配方中删除 "breadcrumbs" 成分=14=]函数。

在那种情况下,也许您可​​以采取稍微不同的方法,通过 Array#filter 方法从食谱 todo 数组中删除成分?

您可以按以下方式使用 filter() 通过以下过滤逻辑 "filter out"(即删除)todo 数组中的 "breadcrumbs" 成分:

// Keep any ingredients that do not match ingredient (ie if ingredient
// equals "breadcrumbs")
todo.filter(todoIngredient => todoIngredient !== ingredient) 

您可以考虑通过以下方式修改 removeIngredient() 功能;

  • 向函数参数添加一个额外的 ingredient 参数。这允许您指定要从对应于 recipeId

  • 的配方中删除的成分
  • 并介绍 filter() 所描述的想法:


const removeIngredient = (recipeId, ingredient) => {

    const recipe = recipes.find(recipe => recipe.id === recipeId)

    if(recipe) {

        // Filter recipe.todo by ingredients that do not match  
        // ingredient argument, and reassign the filtered array 
        // back to the recipie object we're working with
        recipe.todo = recipe.todo.filter(todoIngredient => 
                                         (todoIngredient !== ingredient));
    }

}

现在,当您为每种成分引入 "remove" 按钮时,您将按如下方式调用 removeIngredient()

var recipeId = /* got id from somewhere */
var ingredientText = /* got ingredient from somewhere */

removeIngredient( recipeId, ingredientText );

希望对您有所帮助!