Как обновить массив корзины, когда у вас в корзине несколько объектов в соответствии с условиями?

Я новичок в JS. У меня есть сведения о продукте как объекты. Мне нужно обновить массив корзины одним щелчком мыши,

if (cart=== null)=> qty = 1 => push to cart array ;
else if ( same name && same lense ) => updating qty+1; (bcz there is a item that fulfill that condition) ;

else if ( same name && different  lense ) => qty = 1;=> then push to cart array;

else  ( different name && different lense  ) => qty = 1;=> then push to cart array;

Но когда я нажимаю (с таким же именем и той же линзой), должно быть обновлено количество элементов (с таким же именем и той же линзой). но он обновляет только количество index [0]. Как мне решить эту проблему?

Это мой массив тележек

let cart = JSON.parse(localStorage.getItem('productArray')) || [];``
> //new item object//
>//lense client has severel option//
const cartItem = {
    pic: singlePic.src,
    name: singleProductName.textContent,
    qty: 0,
    price: singleProductPrice,
    lense: "",
};
function addToCart() {
    //no item
    if (JSON.parse(localStorage.getItem('productArray')) == null) {
        //update the cart
        cartItem.qty = 1;
        //push to the cart
        cart.push(cartItem);
        localStorage.setItem('productArray', JSON.stringify(cart))
        // update the cart after the condition
        cart = JSON.parse(localStorage.getItem('productArray'))
    } else {
        // cart has some items
        for (let oldItem of cart) {
            if (cart.some(oldItem => oldItem.name === cartItem.name && oldItem.lense === cartItem.lense)) { oldItem.qty += 1
                // replace order with updated cart 
                localStorage.setItem("productArray", JSON.stringify(cart));
                cart = JSON.parse(localStorage.getItem("productArray"))
            }
            else if (cart.some(oldItem => oldItem.name === cartItem.name && oldItem.lense !== cartItem.lense)) {
                cartItem.qty = 1
                cart.push(cartItem)
                localStorage.setItem('productArray', JSON.stringify(cart))
                cart = JSON.parse(localStorage.getItem("productArray"))
            }
            else {
                cartItem.qty = 1
                cart.push(cartItem)
                localStorage.setItem('productArray', JSON.stringify(cart))
                cart = JSON.parse(localStorage.getItem("productArray"))

            }
        }
    }

person ManojFer    schedule 12.11.2020    source источник


Ответы (1)


Не зная слишком много о потребностях вашего приложения, вот базовая реализация обновления коллекции.

// Example cart array (typical data structure)
let cart = [
    {
        id: 1,
        name: "Product 1",
        quantity: 1
    },
    {
        id: 2,
        name: "Product 2",
        quantity: 2
    }
]

// Function to handle updates
const update_cart = ( id, quantity, name ) => {
    let item = cart.find( item => item.id === id )
    // Product is already in cart, need to increment
    if ( item ) { 
        item.quantity = item.quantity + quantity
    }
    // Product is not in cart, need to add it
    else {
        cart.push({
            id,
            name,
            quantity
        })
    }
}

// Update a product in the cart
update_cart(1, 2, "Product 1")
console.log(cart)

// Add a new product to the cart
update_cart(3, 2, "Product 3")
console.log(cart)

Этот тип приложения обычно обрабатывается API. Но это обязательно укажет вам верное направление

person Jordan Quartermain    schedule 12.11.2020