Home > other >  How to set array key that does not exist yet in javascript?
How to set array key that does not exist yet in javascript?

Time:09-07

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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