简体   繁体   中英

remove and replace item from object in array javascript

I have read and tried all of the posts of SO on this subject, but for some reason none of the answers are providing the desired effect.

I have written a shopping basket program and once the user clicks the'Buy now' button I wish to make POST request containing an object with the users order.

Problem

The user has the option to purchase three different items. Each time the user clicks on an item, which is a html input box, to increase the amount they wish to purchase I want to update the object to only contain the latest amount chosen.

In its simplest format the basket, when initiated, looks like this :

 var basket = {items:[
                    {item:"Trousers", quantity:1, cost:"10"},
                    {item:"Trainers", quantity:1, cost:"5"},
                    {item:"Jacket", quantity:1, cost:"30"}
                ]}

Each time the user clicks the input button I wish for the basket to be updated so if the user clicked to increase the jacket to a quantity of 3, and the trousers to 4 I want the object to look like this:

 var basket = {items:[
                        {item:"Trousers", quantity:4, cost:"40"},
                        {item:"Trainers", quantity:1, cost:"5"},
                        {item:"Jacket", quantity:3, cost:"90"}
                    ]}

Then if a user decides to reduce the number of trousers by 1, to 3, I would want the basket.items object to look like this:

 var basket = {items:[
                            {item:"Trousers", quantity:3, cost:"30"},
                            {item:"Trainers", quantity:1, cost:"5"},
                            {item:"Jacket", quantity:3, cost:"90"}
                        ]}

I have written the code for all the calculations etc. so this is not the issue but the issue is to update basket.items to only contain the three items listed above at once, with the latest data.

I cannot use the filter method as this needs to work in older versions of IE. I have tried all solutions listed in this and this along with many more but none of these answers are providing the solution I am looking for.

Let me know if any further information is required.

try this:

var basket = {
    items: [

    {
        item: "Trousers",
        quantity: 1,
        cost: "10"
    }, {
        item: "Trainers",
        quantity: 1,
        cost: "5"
    }, {
        item: "Jacket",
        quantity: 1,
        cost: "30"
    }]
};

function updateBasket(item) {
    basket.items = basket.items.map(function (product) {
        if (product.item == item.item) return item;
        else return product;
    });
}

updateBasket({
    item: "Jacket",
    quantity: 9,
    cost: "30"
});
updateBasket({
    item: "Trainers",
    quantity: 9,
    cost: "30"
});
console.log(basket)
  • Cost should be a number and not string.
  • If you are not keeping a global object for what is the price of 1 item then once you have updated your basket object you will loose the information on price of 1 item and you wouldn't know how much to increase the price.

Considering same, below would be my recommendation of changes:

 var basket = {items:[
                        {item:"Trousers", quantity:4, itemCost:40, totalCost:40},
                        {item:"Trainers", quantity:1, itemCost:5, totalCost:5},
                        {item:"Jacket", quantity:3, itemCost:90, totalCost:90},
                    ]}

function updateQuantity(itemName, qIncreaseBy, qDecreaseBy){
    console.log(basket);
    for(var propt in basket.items){
        if(basket.items[propt].item == itemName){
            if(qIncreaseBy != 0){
                basket.items[propt].quantity = (basket.items[propt].quantity + 1);
                basket.items[propt].totalCost = (basket.items[propt].totalCost + basket.items[propt].itemCost);
            } else{
                basket.items[propt].quantity = (basket.items[propt].quantity - 1);
                basket.items[propt].totalCost = (basket.items[propt].totalCost - basket.items[propt].itemCost);
            }
            break;
        }
    }
    console.log(basket);
}

Usage:

updateQuantity("Trainers", 0, 1);  //To add item
updateQuantity("Trainers", 1, 0)  //To remove item

Don't know if for you having an array of objects is mandatory if that's not the case you can structure your data differently, for instance

basket = { items : { item_1 : { quantity: 1, cost: 1 } } }

so updating the basket it will be simply

function updateBasket(item, value) {
  // item -> item_1
  // value - > { quantity: 2, cost: 2}
  basket['items'][item] = value;
}

To be honest, I think the problem could be solved if you kept your data in a little different way. For example, something like this

var products  = {
    trousers:0,
    jackets:0,
    trainers:0,
};

var prices = {
    trainers:5,
    jackets: 30,
    trousers: 10
}


//to increase the amount of products after user event
products.jackets  +=2;
products.trainers +=3;
products.trousers +=1;

//finally generate your desired format
var basket = {items:[]};

for(product in products){
   basket.items.push({
       item: product,
       quantity: products[product],
       cost: products[product]*prices[product]
   });
}

console.log(basket);

You can see that basket is now in your desired format :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM