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
Create the object if not exist with
cart[key] = cart[key] ? cart[key] : {};
You’d need to create the property as an empty object first:
To do that conditionally, check if it exists first:
This is what the logical nullish assignment (??=) is for:
So you can use it: