Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!