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

68
Views
How to add multiple objects to local storage with the same key

I have this piece of code that reads data from an excel sheet, turns them into objects and then display their details in a neat product card

let allHoodies = [
  ['Hoodie', 'Purple', 'Cotton', '$39.99', 'image/items/hoodies/hoodie(1).jpg'],
  ['Hoodie', 'Blue', 'Cotton', '$39.99', 'image/items/hoodies/hoodie(2).jpg'],
  ['Hoodie', 'Green', 'Cotton', '$39.99', 'image/items/hoodies/hoodie(3).jpg']
]

allHoodies.forEach((element, index) => {
  let obj = {}
  obj.id = index
  obj.type = element[0]
  obj.color = element[1]
  obj.material = element[2]
  obj.price = element[3]
  obj.imagesrc = element[4]
  allHoodies[index] = obj
})

//Evaluating each hoodie and displaying its information in HTML
allHoodies.forEach(function(hoodie) {
  let card = `
        <div class="card">
            <img class="product-image" src="${hoodie.imagesrc}">
            <h1 class="product-type">${hoodie.type}</h1>
            <p>Color: ${hoodie.color}</p>
            <p>${hoodie.material} <a href="#" onclick="addToStorage(${hoodie.id})">Read more</a> </p>
            <p class="price">${hoodie.price}</p>
            <p><button>Buy</button></p>
        </div>
    `;

  // Add the card to the page
  document.getElementById('product-container').innerHTML += card;
});

What I'm trying to do is, upon clicking "Buy", it adds multiple items to the local storage although I'm struggling to do it and add multiple ones, it keeps on adding only 1 of them and overwriting the previous one (I'm assuming due to the fact that they have the same key)

Here's what I've tried (which works, but its not my goal):

function addToCart(id){
    let hoodie = hoodies[id];
    localStorage.setItem('item', JSON.stringify(hoodie));
}

and then I simply add the addToCart() function to the button, would someone guide me and help me figure out how I could actually add multiple ones to the local storage and not just keep overwriting? Expected result: expected result

Runnable JSFiddle snippet

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use localStorage#getItem to get the current list, and JSON#parse to convert it to an array of objects. Then, use Array#push to add the current item, and finally, use localStorage#set and JSON#stringify to save the updated list:

function addToCart(id) {
  try {
    const hoodie = allHoodies[id];
    if(hoodie) {
      const items = JSON.parse(localStorage.getItem('items') || "[]");
      items.push(hoodie);
      localStorage.setItem('items', JSON.stringify(items));
    }
  } catch(e) {
    console.log('error adding item');
  }
}

Function to show the saved list:

function displayProductsinCart() {
  const products = JSON.parse(localStorage.getItem("item") || "[]");
  document.getElementById("item-container").innerHTML = products.reduce((cards, product) =>
    cards + `<div class="card">
            <img class="item-image" src="${product.image}">
            <h1 class="product-type">${product.type}</h1>
            <p>Color: ${product.color}</p>
             <p>${product.description}</p>
            <p class="price">${product.price} </p>
            <p><button>Buy</button></p>
        </div>
    `, '');
}

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!