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

173
Views
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 answers
Answer question

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