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

时间:2019-01-07 20:15:36

标签: javascript arrays javascript-objects array-splice

我正尝试根据数组中的title属性从对象数组中删除特定项目。我一直遇到一个问题,可以查看数组项目,但是我无法根据在我的remove函数中输入的参数将项目从数组中拼接出来。我只是从函数中的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编号或key拼接该项目是到目前为止,我无法使用已经尝试过的功能以及在Stackoverflow上发现的有关对象,数组和拼接方法的信息。

1 个答案:

答案 0 :(得分:1)

如果我理解正确(在阅读了代码中的注释尝试之后),则您正在尝试从与传递给id的{​​{1}}相对应的食谱中删除“面包屑”成分功能。

在那种情况下,也许您可​​以采用一种稍微不同的方法来通过Array#filter方法从配方removeIngredient()数组中删除成分?

您可以通过以下过滤器逻辑,通过以下方式使用todofilter()数组中“过滤”(即删除)“面包屑”成分:

todo

您可以考虑通过以下方式修改// 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)); } }

removeIngredient()

希望这会有所帮助!

相关问题