0

Let's say I have the following class...

Class Person {
   constructor(name, drives = false) {
      this.name = name;
      this._drives = drives;
   }

   get drives() {
      return this._drives;
   }

   set drives(drives) {
      this._drives = drives;
   }
}

Now let's say that I store a bunch of "Person" objects in localstorage. Now I want to loop through the the localstorage and find the "Person" that does not drive (I created 1 out of 5 who has _drives as TRUE). When I do this, they all come back as undefined...why?

const testFunction = () => {
for (let i = 0; i <= localStorage.length; i++) {
    const key = localStorage.key(i);
    const storedObj = JSON.parse(localStorage.getItem(key));


    if (!storedObj.drives === true) {
        console.log(storedObj.drives);
    }
  }
}

testFunction();

What's wrong here?

Ctsa3
  • 123
  • 1
  • 1
  • 7
  • 4
    Any method gets removed from the object when it gets stringified. – Mina Jun 24 '22 at 14:43
  • 1
    @mina - ahhh okay that makes sense! What alternatives would you say I have? Just call the _drives directly? Does that pose any issues/risks? – Ctsa3 Jun 24 '22 at 14:47
  • 3
    If you need a `Person`, then just create one from the stored information `new Person(storedObj.name, storedObj._drives)` otherwise, use `_drives` or define a custom serialiser for `Person`. Or even give it a factory method to instantiate from JSON, so it can handle serialise+deserialise itself. – VLAZ Jun 24 '22 at 14:53

0 Answers0