6

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.

1
  • 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 Commented Feb 27, 2016 at 20:24

1 Answer 1

5

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"); 
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.