【问题标题】:Have a duplicate of an object, or how to multiply it拥有一个对象的副本,或如何将其相乘
【发布时间】:2022-01-31 08:28:23
【问题描述】:

我有一个装有苹果和橙色物体的购物车。我希望能够添加两次苹果,但我不确定如何将“fruit1”对象定位两次,以便在购物车中显示 2 个苹果。我基本上想用“2个苹果”更新购物车数组,价格“价值”翻倍,1个橙色)

module.exports = {
  shoppingCart: function () {
    //create empty cart array
    theCart = [];
    // all fruits
    let fruitProducts = [
      {
        fruit1: 'Apple',
        price: 4.95,
      },
      {
        fruit2: 'Orange',
        price: 3.99,
      },
    ];
    //push the objects into the empty array using the apply method -- add items to the cart
    Array.prototype.push.apply(theCart, fruitProducts);

    //remove items from the cart by calling this function
    function removeAllItems() {
      if ((theCart.length = !0)) {
        theCart = [];
      }
    }
    //removeAllItems();

    console.log(theCart);
  },
};

【问题讨论】:

  • 建议: 1. 在每个购物车条目中添加数量和小计字段。 2. 不要使用fruit1 和fruit2,只使用fruit - 或者更好的是item。
  • 感谢您的帮助,约翰。仍在努力,但绝对有帮助

标签: javascript node.js arrays object


【解决方案1】:

使用.map()。添加属性qtytotal 并传递代表每个项目数量的数字(...amounts 例如1, 2, 5)。

const fruit = [{
    "fruit": "Apple",
    "price": 4.95
  },{
    "fruit": "Orange",
    "price": 3.99
  }
];

const shop = (product, ...amounts) => {
  let qty = [...amounts] || [];
  
  let cart = product.map((item, count) => {
    item.qty = qty[count] || 0;
    item.total = parseFloat((item.qty * item.price).toFixed(2));
    return item;
  });
  return cart;
};
  
console.log(shop(fruit, 1, 3));
console.log(shop(fruit, 4));
console.log(shop(fruit));
console.log(shop(fruit, 1, 3, 2));

【讨论】:

  • 太好了,很高兴为您提供帮助。我更新了答案并简化了检查。
  • 再次感谢 zer00ne!欣赏它
【解决方案2】:

您似乎在问如何从数组中找到一个对象然后复制它。

首先,找到fruit1:

const apple = fruitProducts.find(fruit => “fruit1” in fruit);

接下来,要将该对象的副本推送到您的购物车,您可以使用扩展运算符进行浅拷贝:

theCart.push(…apple);
theCart.push(…apple);

话虽如此,更好的解决方案是保留一个对象列表,这些对象的属性是水果、数量和价格。然后,您可以在将商品添加到购物车后计算总价。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 2012-07-18
    • 2021-02-24
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    相关资源
    最近更新 更多