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

142
Visualizações
How can I store data in a JavaScript Array so it can be stored in local storage?

I'm trying to build a basic web store and I'm looking for a way to store data that I already have in an Excel sheet in a JavaScript array so that I can store it in the local storage if the buyer clicks on "Add to cart", for example: I have this data right here:

['Hoodie','Purple','cotton authentic',' Only £39.99','images/items/hoodies/hoodie (1).jpg']

['Hoodie','Light Blue','cotton authentic',' Only £39.99','images/items/hoodies/hoodie (2).jpg']

['Hoodie','Green','cotton authentic',' Only £39.99','images/items/hoodies/hoodie (3).jpg']

as you can see, it's the type of clothing, color, description, price and source of image

how can I store this in a JavaScript array so that I can create a function that upon clicking a button, adds the specific item in local storage?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

First off... from a data structure point of view, your solution is: interesting

['Hoodie','Purple','cotton authentic',' Only £39.99','images/items/hoodies/hoodie (1).jpg']

['Hoodie','Light Blue','cotton authentic',' Only £39.99','images/items/hoodies/hoodie (2).jpg']

['Hoodie','Green','cotton authentic',' Only £39.99','images/items/hoodies/hoodie (3).jpg']

Generally, in an array, you want to have multiple things that are all the same kind of thing. Yes, here each hoodie is represented as an array... and all the elements of each array are strings... but each string represents some entirely different type of thing.

Really, you should be using objects to store the hoodies:

{
    type: 'Hoodie',
    color: 'Purple',
    material: 'cotton authentic',
    price: '£39.99',
    image: 'images/items/hoodies/hoodie (1).jpg'
}

Now you have a single thing that has specific attributes each with a value

To show all of your hoodies, you have your array.. but now you load that array with those objects instead of having separate arrays

var hoodieArray = [{
    type: 'Hoodie',
    color: 'Purple',
    material: 'cotton authentic',
    price: '£39.99',
    image: 'images/items/hoodies/hoodie (1).jpg'
},
{
    type: 'Hoodie',
    color: 'Light Blue',
    material: 'cotton authentic',
    price: '£39.99',
    image: 'images/items/hoodies/hoodie (2).jpg'
},
{
    type: 'Hoodie',
    color: 'Green',
    material: 'cotton authentic',
    price: '£39.99',
    image: 'images/items/hoodies/hoodie (3).jpg'
}]

Now, you have a way to store, within a single key in the localStorage, the array of separate objects each with its list of attributes simply by passing in JSON.stringify(hoodieArray)

about 4 years ago · Juan Pablo Isaza Relatório

0

If you have the array in numbers and want to clean them up to array of object.

For instance, let say you have arrays like the following :

let allArray = [
    ['Hoodie', 'Purple', 'cotton authentic', ' Only £39.99', 'images/items/hoodies/hoodie (1).jpg'],

    ['Hoodie', 'Light Blue', 'cotton authentic', ' Only £39.99', 'images/items/hoodies/hoodie (2).jpg'],

    ['Hoodie', 'Green', 'cotton authentic', ' Only £39.99', 'images/items/hoodies/hoodie (3).jpg']

]

provided you are sure of the position of each element in the sub array, you, the code below will transform all to array of object.

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

you can have a look at what you get in the console

console.log(allArray)

so, you can then add the reformed array to localstorage like this :

localStorage.setItem("mycart", JSON.stringify(allArray))

However, in an ideal scenario, items are added to the cart one at a time. To add an item at a time you can write a function to add item to cart and another one to get cart items as given below

addToCart(item) {
        let items = getCartItem()
        items = items == null ? [] : items
        let found = items.find(x => x.somethingUnique == item.somethingUnique)
        if (found == null || undefined) {
            items.push(item)
            localStorage.setItem("mycart", JSON.stringify(items))
            return true;

        }
        return false;

    }

Note

 let found = items.find(x => x.somethingUnique == item.somethingUnique)

Replace somethingUnique with anything that is unique to each object, like ID etc. This is to check if an element already exist in the cart, and therefore avoids duplicates with the code

getCartItem() {
        let item = localStorage.getItem("mycart")
        item = item == null || undefined ? null : JSON.parse(item)
        return item;
    }

I hope this helps.

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