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.
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));
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With