Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

61
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda