Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
An error arises when I add a key value to an object

As the title says, I need a code to make this work. The code is:

let count = 0;
for (const payment of paymentButtons) {
    if (payment.checked) {
        count = 0;
        window.confirm(acc+" added "+quantity+" sized: "+size+" "+name+" for "+price+" with "+shipping+" to cart");

        let count2 = 1;
            
        var tocart = {
            name: name,
            price: price,
            size: size,
            quantity: quantity,
            shipping: shipping
        };

        console.log(tocart)

        var cart = JSON.parse(localStorage.getItem("cart"));
        for (const key in cart) {
            count2++;
        }

        var naming = "tocart"+count2.toString();
            
        cart[naming] = tocart;
        console.log(cart)
            
        var json = JSON.stringify(cart);
        localStorage.setItem("cart", json);
            
        break;
    }
}

but it gives an error of type:

Uncaught TypeError: Cannot set properties of null

I have tried everything I could but I couldn't find the answer. how can I make it to add the key value to the object?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Are you sure that localStorage has an object with key 'cart'?

localStorage.getItem("cart")

You can add default value (empty object) for the case of it has not:

var cart = JSON.parse(localStorage.getItem("cart")) ?? {};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda