Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
    
in general you want to push the objects in the array, then set the array in the localStorage using the set method. When you want to get the array back you will have to use the get method – Akis Feb 27 at 20:24

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"); 
share|improve this answer
2  
You don't need to stringify with this library, because the set function utilizes angular's toJson() method under the hood. Similarly, the get method JSON.parse()s the item to return. No need for that either. – Bennett Adams Feb 27 at 20:11
    
thanks for telling, gonna edit the answer – Akis Feb 27 at 20:13
    
Thank you, worked as expected. – GreenDome Feb 29 at 18:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.