Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - How to store objects in an array and local storage

How I can store multiple objects into an array and then into local storage so that I can get all objects when required using a loop.

example objects:

var newMsg = {
      sentDate: msgDate,
      sentTime: msgTime,
      msgTitle: "message title",
      msgDesc: "message desc"
    };

Currently I'm using https://github.com/grevory/angular-local-storage#configuration-example angularjs module but struggling to store and retrieve objects from an array.

I have tried the following code:

msgArray = [];
var savedMsgs = localStorageService.set("wimmtkey", newMsg);

    msgArray.push(savedMsgs); 
    console.log(savedMsgs);

This outputs 'true' in the console but expecting to see the stored object. Please also advise to loop through the array to retrieve the objects. Thanks.

like image 912
GreenDome Avatar asked Feb 27 '16 19:02

GreenDome


People also ask

Can I store an array in localStorage?

Save Array In localStorageYou can save the array by using the setItem method. const myBlogs = ["https://catalins.tech", "https://exampleblog.com"]; localStorage. setItem('links', JSON. stringify(myBlogs));

Can you store objects in localStorage?

In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON. stringify method, then back to objects with the JSON.


1 Answers

Some more code would be useful but for angular-local-storage this is the way that you push objects into array before saving the array in the localStorage:

var msgArray = [];
var newMsg = {
    sentDate: msgDate,
    sentTime: msgTime,
    msgTitle: "message title",
    msgDesc: "message desc"
};

//you can push all the objects here before saving to the storage
//maybe you have a forEach here, pushing the objects? Who knows
msgArray.push(newMsg); 

//the array is now set in the storage
localStorageService.set("wimmtkey", msgArray); 

//the array obtained from local storage
var obtained_array = localStorageService.get("wimmtkey"); 
like image 125
Sarantis Tofas Avatar answered Oct 14 '22 00:10

Sarantis Tofas