Remove an array item nested inside of an object

18
January 08, 2019, at 01:10 AM

I'm trying to remove a specific item from an objects array based on the title attribute in the array. I keep running into a problem where I can view the array item, but I'm not able to splice the item out of the array based on the parameters entered in my remove function. I'm just getting the error message back from my else statement in the function.

I've tried using find, forEach, findIndex and match that case in order to test out removing the result based on the index, or the text value of the key 'text'. I commented out all of the functions I tried prior to searching for the answer in the forum recommendations. All of my recipe functions are working, along with my createIngredient function, which adds an object to the recipe array. But the removeIngredient function I've been trying to get to work, isn't because of the problems mentioned above.

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()

OUTPUT

{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

So I'm able to view the output I printed above and see each item in the ingredients array, but trying to splice the item based on the index number or key is not working for me with the functions I have already tried and the info I have found on Stackoverflow about objects, arrays and the splice method so far.

Answer 1

If I am understanding correctly (after reading the commented out attempts in your code), you are trying to remove the "breadcrumbs" ingredient from the recipe that corresponds to the id passed to the removeIngredient() function.

In that case, perhaps you could take a slightly different approach to removing the ingredient from the recipes todo array, via the Array#filter method?

You could use filter() in the following way to "filter out" (ie remove) the "breadcrumbs" ingredient from the todo array via the following filter logic:

// Keep any ingredients that are not "breadcrumbs"
todo.filter(ingredient => ingredient !== 'breadcrumbs') 

So, you might consider something like the following:

const removeIngredient = (id) => {
    const recipe = recipes.find(recipe => recipe.id === id)
    if(recipe) {
        // Filter recipe.todo by ingredients that are not breadcrumbs, and 
        // reassing the filtered array back to the recipie object we're working
        // with
        recipe.todo = recipe.todo.filter(ingredient => ingredient !== 'breadcrumbs');
    }
}

Hope this helps!

READ ALSO
“Uncaught TypeError: this._socket.write is not a function” on client.connect

“Uncaught TypeError: this._socket.write is not a function” on client.connect

I am trying to create a OPCUA Client in nwjs with the node-opcua package

44
Why this code isnot working , i trying to add condition into condition using if statment and check class name [on hold]

Why this code isnot working , i trying to add condition into condition using if statment and check class name [on hold]

this the code that i wrote and this don't fire if statements correctly and i don't regognize the error where when it fire it do nothing what should i do ??

35
Is it possible to wait until a task in the windows taskmanager has stopped?

Is it possible to wait until a task in the windows taskmanager has stopped?

So basically, i want python to run another programm and wait till that program is not visible in the taskmanger and then continue with the scriptAny Ideas?

24