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

177
Visualizações
how to save an array in localstorage

I currently have this code, it saves in localstorage, but it generates several objects, I would like to store everything in a single array

getItemById(id) {
return this.cacheS.getOrSetCache(`StoreService_getItemById_${id}_${this.layout.emp.id}`, this.http.get(`${environment.API_URL}item/getById/${id}`), 300000);
}

  getOrSetCache(key: string, request: Observable<any>, msToExpire = 3600000): Observable<any> {
let cache: any = {};

cache = JSON.parse(localStorage.getItem(key));

return (cache?.data && (cache?.exp > Date.now())) ?
  of(cache.data) :
  request.pipe(tap(v => {
    localStorage.setItem(key, JSON.stringify({data: v, exp: (Date.now() + msToExpire)}));
  }));
}

enter image description here

This code works, but I wanted to join all the StoreService_getItemById_, with this code it makes the array in a single StoreService_getItemById_, if you notice the image has several local storage with the name StoreService_getItemById_, I would like it to have only one and inside that it had the objects in array format

        localStorage.setItem(key, JSON.stringify({data: [v], exp: (Date.now() + msToExpire)}));

I wish it were the same "item" enter image description here

enter image description here

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

It sounds like you want to append items to an array in local storage. The thing is, local storage only saves strings. You can parse the string to convert it into an array, append a new item, then overwrite the old string.

const key = 'my-array-key';
const someData = { name: 'name', id: 'abcdef' };
const msToExpire = 5000;

// Convert string to array, initializes empty array if string is empty
let arr: any[] = [];
let string = localStorage.getItem(key);
if (string) arr = JSON.parse(string);

// Push a new item and overwrite the old string
arr.push({data: someData, exp: (Date.now() + msToExpire)});
localStorage.setItem(key, JSON.stringify(arr));

I'm not really sure how you want to structure that function but this example should give you the general idea.

about 4 years ago · Santiago Trujillo 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