更新嵌套数组中的嵌套数组

scrmhdk:

我在下面的数组结构中有一系列的食谱:

[
  {
    "brandName": "Piatto",
    "_id": "1234",
    "name": "Test",
    "rate": 89,
    "baseQuantity": 1000,
    "baseUnit": "gm",
    "details": [
      {
        "_id": "5f3aadd5d756e9341ef74e2b",
        "quantityInRecipe": 0,
        "costOfRawMaterial": 0,
      },
      {
        "_id": "5f3aadd5d756e9341ef74e2a",

        "quantityInRecipe": 0,
        "costOfRawMaterial": 0
      }
    ],
    "__v": 0
  },
  {
    "brandName": "Piatto",
    "_id": "5678",
    "name": "Macaron Shell",
    "details": [
      {
        "_id": "5f397abb59ad0ba71f27fa93",
        "rate": 12,
        "quantityInRecipe": 121,
        "costOfRawMaterial": 14.52,
      },
      {
        "_id": "5f397adb59ad0ba71f27fa94",
        "quantityInRecipe": 122,
        "costOfRawMaterial": 17.08
      },
      {
        "_id": "5f36cccc875da6156c9a0782",
        "quantityInRecipe": 330,
        "costOfRawMaterial": 19.8

      }
    ],
    "baseQuantity": 573,
    "baseUnit": "gm",
    "totalCost": 51,
    "__v": 0
  }
]

我想更新第一个对象(ID:1234)中的“ id 5f3aadd5d756e9341ef74e2b”的值。

到目前为止,我已经能够分别更新对象“ Test”(ID:1234)的数组详细信息,该对象位于下面代码的索引0处。

 
    let tempArray = state.recipeBasicRecipes[index].details;

    let objIndex = tempArray.findIndex(rec => rec._id === id);

    const updatedObj = {
      ...tempArray[objIndex],
      quantityInRecipe: e.target.value
    };

    console.log(objIndex);

    const updatedArray = [
      ...tempArray.slice(0, objIndex),
      updatedObj,
      ...tempArray.slice(objIndex + 1)
    ];
    

我的目标是使用updatedarray更新第一个对象中的详细信息数组。

达克里·丹尼(Dacre Denny):

似乎您需要将updatedArrayback 重新分配给第一个元素的子数组recipeBasicRecipes

state.recipeBasicRecipes[index].details = updatedArray;

必要的原因是,您updatedArray实际上是一个单独的新数组实例(而不是对details您开始子数组的引用),这意味着该details子数组需要“指向”(或引用)您的新数组。updatedArray数组以达到所需的结果。

解决此问题的另一种“不变”方法如下:

const basicRecipe = state.recipeBasicRecipes[index];

/* Obtain new details sub array with updated quanitity data */
const updatedDetails = basicRecipe.details.map((detail) => {
  
  if(detail._id === id) {
    /* If we're iterating the detail matching "id", apply new quantity */
    return {
      ...detail,
      quantityInRecipe: e.target.value
    }
  }
  else {
    return detail
  }
  
});

/* Apply updated details to updated recipe */
const updatedRecipe = {
  ...basicRecipe,
  details : updatedDetails
}
  
/* 
Apply updated recipe to component state 
this.setState({
  ...state,
  [index] : updatedRecipe
})
*/

希望有帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章