如何在switch语句后删除数组对象的情况

问题描述 投票:0回答:3

我有一个菜单系统,我有一些结帐系统的代码,以确定特定商品出现在购物车中的交易/折扣。

这是迄今为止的代码:

        var shampoo = false;
        var dye = false;
        var conditioner = false;


            for (var i in cartArray) {
                switch (cartArray[i].name) {
                        case 'Pantene Pro-V':
                        drinks = true;
                        break;
                        case 'Red Dye':
                        chicken = true;
                        break;
                        case 'Herbal Conditioner':
                        kebab = true;
                        break;
                }
                if (shampoo && dye && conditioner) {
                console.log("yes");
                // shoppingCart.removeItemFromCartAll(cartArray[i].name);
                // window.location.reload(true);
                break;
            }
        }
        if (!shampoo || !dye || !conditioner) {
            console.log("no");
        }

控制台日志在一个完整的随机购物车中显示是,所以这是一个积极的,但我试图将这三个项目作为一个组一起删除,但它不起作用。

以下是我的删除功能的代码:

      obj.removeItemFromCartAll = function(name) {// removes all item name
        for (var i in cart) {
            if (cart[i].name === name){
                cart.splice(i,1);
                break;
            }
        }
        saveCart();
    };

我尝试插入此代码:

     shoppingCart.removeItemFromCartAll(cartArray[i].name);

在每个案例下方,但它最终会在购物车中单独删除项目,而不是一组三个。

这是控制台的样子(数组对象):

       yes

      (4) [{…}, {…}, {…}, {…}]

       0: {name: "Pantene Pro-V", price: 2.5, count: 1, total: 
       "2.50"}
       1: {name: "Red Dye", price: 4, count: 1, total: "4.00"}
       2: {name: "deodorant", price: 2.5, count: 1, total: "2.50"}
       3: {name: "Herbal Conditioner", price: 1, count: 1, total: "1.00"}
       length: 4
       __proto__: Array(0)

请帮忙。谢谢。

顺便说一下,我想删除这三个,并从菜单中将另一个项目添加到购物车中(就像一个包含这三个以降价的价格... FYI)。

编辑 - 在这里评论这部分

 shoppingCart.removeItemFromCartAll(cartArray[i].name); 

删除购物车中的最后一项,并用splice方法替换删除删除整个购物车并打破购物车系统

javascript arrays object if-statement switch-statement
3个回答
0
投票

据我了解此代码,它只能正确删除一个项目

cart.splice(i,1);

在这里,您提供了1,这意味着它将从作为第一个参数提供的索引中删除1个项目。尝试将其更改为3。

更糟糕的情况是,如果你有隆隆阵列,那3个项目不会相继。然后最好你应该创建一些属性,将项目分配给特定组,然后使用数组的filter方法过滤掉你想要删除的项目


0
投票

使用delete关键字

obj.removeItemFromCartAll = function(name) {// removes all item name
        for (var item in cart) {
            if (cart[item].name === name){
                delete cart[item]
                break;
            }
        }
        saveCart();
    };

0
投票

“在每个箱子下方,但它最终会在购物车中单独移除物品,而不是一组三个。”

一组三个或三个单独的项目并不重要,重要的是它们被删除。应考虑诸如客户少于3个销售项目或根本不存在和/或不具有相同顺序的情况。作为过滤器的开关是一个坏主意,你想避免硬编码动态数据(我假设购物车中的商品对于每个客户都是不同的,并且销售商品最终也会改变。)

Demo Outline

  1. list一个表示客户购物车内容的对象数组。
  2. 销售代表当前待售商品的一系列对象。
  3. 将两个数组转换为地图。 var discount = convertToMap(list, "name") var customer = convertToMap(sale, "name")
  4. 将折扣和客户地图相互比较,并将每个匹配的键/值对从折扣合并到客户。
  5. 结果是具有此模式的地图: `[["Muffin Mix - Raisin Bran", {"name":"Muffin Mix - Raisin Bran","price":5.85,"qty":1,"total":2.92,"saved":2.93}], ...]`

演示

// Sale Items - Note the "total" and "saved" values
let sale = [
{"name":"Flavoring - Orange","price":4.57,"qty":1,"total":2.00,"saved":2.57},
{"name":"Muffin Mix - Raisin Bran","price":5.85,"qty":1,"total":2.92,"saved":2.93},
{"name":"Pepsi - Diet, 355 Ml","price":3.63,"qty":1,"total":1.81,"saved":1.82}
]; 

// Cart Items - This represents the customer's cart
let cart = [
{"name":"Plastic Arrow Stir Stick","price":0.75,"qty":1,"total":0.75,"saved":0},
{"name":"Veal - Round, Eye Of","price":22.91,"qty":1,"total":22.91,"saved":0},
{"name":"Calypso - Pineapple Passion","price":8.69,"qty":1,"total":8.69,"saved":0},
{"name":"Sloe Gin - Mcguinness","price":33.27,"qty":1,"total":33.27,"saved":0},{"name":"Wine - Sake","price":28.47,"qty":1,"total":28.47,"saved":0},
{"name":"Dried Figs","price":1.78,"qty":1,"total":1.78,"saved":0},
{"name":"Pepsi - Diet, 355 Ml","price":3.63,"qty":1,"total":3.63,"saved":0},
{"name":"Olives - Moroccan Dried","price":15.17,"qty":1,"total":15.17,"saved":0},
{"name":"Muffin Mix - Raisin Bran","price":5.85,"qty":1,"total":5.85,"saved":0}
];

/*
@ convertToMap(array, key) 
@ Params: array [Array of Objects]..(ex. list)
@         key [String]..............(ex. "name")
@ Converts an Array of Objects to a MAP
@ iNPUT: [{key,...}, {key,...}, {key,...}], key
@ ~~~~~~~~~~~~~~===~~~~~~~~~~~~~~~
@ OUTPUT: [[key, {key,...}], [key, {key,...}], [key, {key,...}]]
*/
const convertToMap = (array, key) => {return new Map(array.map(item => [item[key], item]));};

// Get a Map of sale
const discount = convertToMap(sale, 'name');
// Get a Map of cart
const customer = convertToMap(cart, 'name');

/*
@ mergeMaps(mapA, mapB)
@ Params: mapA [Map]...smaller Map...(ex. [[...], [...]])
@         mapB [Map]...larger Map....(ex. [[...], [...]])
@ Compares MapA to MapB
@ If any matches by value occur, 
@ replace MapB key/value with MapA key/value
*/
const mergeMaps = (mapA, mapB) => {
  for (let key of mapB.keys()) {
    if (mapA.has(key)) {
      mapB.set(key, mapA.get(key));
    }
  }
  return mapB;
};

let shoppingA = mergeMaps(discount, customer);

console.log(shoppingA.get("Sloe Gin - Mcguinness"));
console.log("~~~~~~~~~~~~~~~~~~~~~-====-~~~~~~~~~~~~~~~~~~~~~");

// [OPTION] Convert new Map to a 2D Array 
let shoppingB = Array.from(mergeMaps(discount, customer));

console.log(shoppingB);
© www.soinside.com 2019 - 2024. All rights reserved.