I have a Student Java Script object as follows:
function Student(name, grade){
this.name = name;
this.grade = grade;
}
I know I can store and retrieve this object to/from Local Storage using JSON.stringify() and JSON.parse() method. It works fine. But my problem is below.
I want to introduce a new property 'subjects' of Set() type that takes unique values and store this Student object in Local Storage. My saveStudent() method is as follows:
function saveStudent () {
student = new Student("Rajib","1st");
var subjects = new Set();
subjects.add("Mathematics");
subjects.add("Science");
subjects.add("English");
console.log(subjects);
student.subjects = subjects;
window.localStorage.setItem("student", JSON.stringify(student));
}
I can store this object in Local Storage without any error and also my console displays the 3 subjects properly. But when I try to retrieve this Student object from Local Storage, I get Student object with all the values except 'subjects' which is empty. May I know why?
My getStudent() method is as follows:
function getStudent () {
var student = JSON.parse(window.localStorage.getItem("student"));
console.log(student);
}
My console shows
Object { name: "Rajib", grade: "1st", subjects: {} }
Is there anyway to store nested object(where property of object contains another object) as such in Local Storage and retrieve with all its properties and values?
Note: I can solve the above by serializing to String of Subjects and then deserializing again. But I want to avoid that and want to do it in pure Java Script or OOPs way.