I am a beginner to Javascript. I am trying to print an array of objects from LocalStorage. I stringified the array before putting it in, then parsed it when retrieving it. In addition, I added a 'toString()' method to my object's class.
class Book {
constructor(title, commentary) {
this.title = title;
this.commentary = commentary == undefined ? "" : commentary;
this.date = new Date();
}
toString() {
return `"${this.title}"`;
}
}
var mybooks = [];
mybooks.push(new Book("The Hobbit"));
mybooks.push(new Book("Pride and Prejudice"));
console.log("books: " + mybooks.toString());
localStorage.setItem("mybooks", JSON.stringify(mybooks));
var books = JSON.parse(localStorage.getItem("mybooks"));
console.log("books: " + books.toString());
However, here is the output:
books: "The Hobbit","Pride and Prejudice"
books: [object Object],[object Object]
Ideally, the second line should be like the first line. Any help would be appreciated! Thank you.
I've looked online and have seen several similar threads, but most of them store arrays of primitives, or didn't convert the array to a string before storing it, or were the result of typos.
toStringmethod fromObject.prototype. On the contrary, it's rather recommended!JSON.parsedoes create plain objects instead of constructingBookinstances. You'll need to use a reviver callback, or usebooks.map(object => new Book(…)). Preferably, create a staticBook.fromJSONto help you with that - in particular, if you want to restore the.date(as you currently can't pass that to your constructor).