【问题标题】:Update an array of objects with an array of updated values使用更新值数组更新对象数组
【发布时间】:2021-07-08 12:16:57
【问题描述】:

我有一系列购物车。我想更新请求对象中的产品数量。即

cart: [
    {
      quantity: 2,
      _id: 60757fdca818d96ed87c852e,
      productID: 101,
      vendorID: 60642991015028ba0a6ce72c
    },
    {
      quantity: 2,
      _id: 607584b4a818d96ed87c852f,
      productID: 102,
      vendorID: 60642991015028ba0a6ce72c
    }
  ]

我有一系列产品 ID 和数量,例如:

updatedValues: [
           { productID:'101', quantity: 3 },
           { productID:'102', quantity: 1 } 
         ]

我想像这样更新它们:

cart: [
    {
      quantity: 3,
      _id: 60757fdca818d96ed87c852e,
      productID: 101,
      vendorID: 60642991015028ba0a6ce72c
    },
    {
      quantity: 1,
      _id: 607584b4a818d96ed87c852f,
      productID: 102,
      vendorID: 60642991015028ba0a6ce72c
    }
  ]

这可能的逻辑是什么?

【问题讨论】:

  • 请提供您尝试过的代码,以便我们更好地引导您找到答案。
  • 我没有得到结果,所以我没有代码。有什么可能的解决方案?
  • 请参阅如何提问。这解释了为什么您没有得到答案。 => stackoverflow.com/help/how-to-ask
  • 嗯,你是对的。我实际上然后自己想出了解决方案。

标签: node.js mongoose rest


【解决方案1】:

我找到了解决办法:

  updatedValues.map((product) => {
    cart.find((item) => {
      if (item.productID === product.productID) {
        item.quantity = product.quantity;
      }
    });
  });

有没有其他优化的方法来获取它?

【讨论】:

    【解决方案2】:

    所以要更新上一个。状态数组你可以先循环遍历上一个。 state 然后逐项运行一个函数,该函数遍历包含更新值的新数组并找到指向 prev 内的特定项目。项目的状态并分别更新它们。这里我使用数组的 find 函数,.find() 循环遍历更新值数组,如果它找到它返回找到的对象,否则返回 undefined。 所以,我认为这可能会对您有所帮助:

      /* Here I'm assuming you already have original array coming from somewhere, inside results
     variable and updationArray represents the array containing updated information **/
    
    const updatedResults = results.map((res)=>(modifyItem(res, updationArray)));
    
    /* This function runs when we run the map function on results item wise **/
    const modifyItem = (item, updationArray) => {
      const modifiedResult = updationArray.find(({productID})=> (productID === String(item. productID)));
      if(!modifiedResult)
         return item;
      return { ...item, ...modifiedResult }
    }
    

    所以updatedValues 变量应该包含具有更新值的数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 2021-04-29
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      相关资源
      最近更新 更多