Madel M6TM
Madel M6TM

Reputation: 45

How to store a complex object javascript

I have a complex object of this type:

class Person {
  constructor(name, age, country) {
    this.name = name;
    this.age = age;
    this.country = country;
  }
  
  setName(name) {
    if (name !== null) this.name = name;
  }
  setAge(age) {
    if (age !== null) this.age = age;
  }
  setCountry(country) {
    if (country !== null) this.country = country;
  }
  
  getName() {
    return this.name;
  }
  
  // ...
}

let person = new Person('Paul', 27, 'Haïti'); // needs to save this Object
console.log(person);

So I would like to know if anyone has an idea on how I can store this Object so that I can access it the next time I open the browser. localStorage doesn't work.

Upvotes: 4

Views: 565

Answers (2)

trincot
trincot

Reputation: 350127

I'd add a static method to the class, that can take a plain object and return an instance of the class in return. You can use Object.create and Object.assign for that.

Demo:

class Person {
  constructor(name, age, country) {
    this.name = name;
    this.age = age;
    this.country = country;
  }
  static from(obj) {
    return Object.assign(Object.create(this.prototype), obj);
  }
  getName() {
    return this.name;
  }
  // ...
}

// Demo
let person = new Person('Paul', 27, 'Haïti');
let serialised = JSON.stringify(person);
// ... write/read serialised to/from localStorage ...
// and then:
let person2 = Person.from(JSON.parse(serialised));
console.log(person2.getName());

Upvotes: 0

Bravo
Bravo

Reputation: 6254

localStorage does work - you just need to use it properly

I added a toJSON method on the class - this returns an array with the constructor parameter values in the right order

class Person {
    constructor(name, age, country) {
        this.name = name;
        this.age = age;
        this.country = country;
    }
    toJSON() {
        return [this.name, this.age, this.country];
    }
    setName(name) {
        if (name !== null) this.name = name;
    }
    setAge(age) {
        if (age !== null) this.age = age;
    }
    setCountry(country) {
        if (country !== null) this.country = country;
    }
    getName() {
        return this.name;
    }
}

To save

const person = new Person("John", 23, "Aussie");
localStorage.setItem('test', JSON.stringify(person));

To load

const revivedPerson = new Person(...JSON.parse(localStorage.getItem('test')));

You don't have to make the toJSON method, but it makes for simple code (if you never need to JSON.stringify an instance of Person)

Upvotes: 1

Related Questions