1

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 3

2

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;
        });
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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] = {};
}

Comments

1

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;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.