簡體   English   中英

如何將嵌套的對象數組推送到數組?

[英]How to push a nested array of objects to an array?

我必須創建一個嵌套的對象數組並將其推送到一個數組中。

我的代碼片段在名為 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

recipes是一個對象數組。 這些對象中的每一個都有ingredients字段,它本身就是一個數組。

recipes本身沒有ingredients字段。

因此,您需要遍歷recipes的元素。 對於每個配方對象,將許多成分推入其ingredients數組。

數組是對象的列表,這些對象可以隨心所欲地復雜化。 我更喜歡創建自定義對象來保存我推送到數組上的所有值,但這是可選的。 我這樣做是為了確保數組中每個條目的結構完全相同。

如果一個對象需要自己保存一個數組——就像在你的食譜成分中一樣——你需要構建那個子數組並將它添加到主對象中,然后再將該主對象添加到主數組中(你可以稍后添加它,但那是更復雜!)。

這是我的意思的一個例子:

// create a recipe object
let recipe = {
  id: "",
  name: "",
  ingredients: ""
}
// create an ingredient object with a constructor to make it easier to populate
function ingredient (recipeid, name, quantity){
  this.recipeid = recipeid;
  this.name = name;
  this.quantity = quantity;
}
// create a recipes array and truncate it (it always seems to start with a blank entry)
let recipes = [];
recipes.length = 0;

// Now create a recipe
function addRecipe() {
  let thisrecipe = Object.create(recipe);
  thisrecipe.id = 1;
  thisrecipe.name = "Scrambled eggs";
  // create a dummy array for the ingredients
  let ings = [];
  ings.length = 0;
  // create a new ingredient object for each ingredient
  // and push that onto the dummy array
  let ing = new ingredient(thisrecipe.id, "eggs", "2");
  ings.push(ing);
  ing = new ingredient(thisrecipe.id, "cream", "6 tbps");
  ings.push(ing);
  ing = new ingredient(thisrecipe.id, "butter", "1 knob");
  ings.push(ing);
  // once all ingredients have been added onto the dummy array, update the recipe object's ingredients property
  thisrecipe.ingredients = ings;
  // finally, push the completed recipe onto the recipes array
  recipes.push(thisrecipe);
}

addRecipe();
console.log(recipes);

顯然,這都是針對一個食譜和三種成分的硬編碼 - 但是,希望它應該為您提供構建完整食譜數組所需的原則

我認為 push() 函數是在屬性上操作而不是它的值。 如果您添加一些額外的行:

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
        let ings = foundRecipeById.ingredients;
        ings.push({
            id: uuidv4(),
            text,
            completed: false
        })
        foundRecipeById.ingredients = ings;
        saveIngredients()
    }
    else {
        // Do something intelligent if the recipe is not found
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM