Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 294
Madel M6TM Avatar asked Jan 19 '26 07:01

Madel M6TM


1 Answers

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)

like image 51
Bravo Avatar answered Jan 20 '26 20:01

Bravo