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

60
Vistas
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 Respuestas
Responde la pregunta

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 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