skip to Main Content

My problem is Uncaught TypeError: Cannot set properties of undefined (setting 'quantity') when I iterate over response array.

$.ajax({
    url: "/cart/sync",
    success: function(response){
        let cart = {};
        Object.keys(response).forEach(key => {
            cart[key].quantity = response[key].product_quantity;
            cart[key].discounted_price = response[key].product_discounted_price;
            cart[key].holding = response[key].product_temp_holding;
        });
    }
});

I want to make cart[newKey] if not exist, how to do that?

3

Answers


  1. Create the object if not exist with cart[key] = cart[key] ? cart[key] : {};

    $.ajax({
        url: "/cart/sync",
        success: function(response){
            let cart = {};
            Object.keys(response).forEach(key => {
                cart[key] = cart[key] ? cart[key] : {};
                cart[key].quantity = response[key].product_quantity;
                cart[key].discounted_price = response[key].product_discounted_price;
                cart[key].holding = response[key].product_temp_holding;
            });
        }
    });
    
    Login or Signup to reply.
  2. You’d need to create the property as an empty object first:

    cart[key] = {};
    

    To do that conditionally, check if it exists first:

    if (!cart[key]) {
      cart[key] = {};
    }
    
    Login or Signup to reply.
  3. This is what the logical nullish assignment (??=) is for:

    The logical nullish assignment (x ??= y) operator only assigns if x is
    nullish (null or undefined).

    So you can use it:

    Object.keys(response).forEach(key => {
        cart[key] ??= {};
        // or similar terms:
        // cart[key] ?? (cart[key] = {});
        // cart[key] || (cart[key] = {});
        cart[key].quantity = response[key].product_quantity;
        cart[key].discounted_price = response[key].product_discounted_price;
        cart[key].holding = response[key].product_temp_holding;
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search