Sobes.tech
Junior

Ako uložiť JavaScriptový objekt do localStorage?

sobes.tech AI

Odpoveď od AI

Použitím JSON.stringify() na serializáciu objektu do reťazca pred uložením a JSON.parse() na deserializáciu reťazca späť na objekt pri načítaní.

// Príklad objektu
const userSettings = {
  theme: 'dark',
  fontSize: 16,
  notifications: true
};

// Uloženie objektu do localStorage
localStorage.setItem('userSettings', JSON.stringify(userSettings));

// Získanie objektu z localStorage
const storedSettings = localStorage.getItem('userSettings');

// Deserializácia reťazca späť na objekt
if (storedSettings) {
  const parsedSettings = JSON.parse(storedSettings);
  console.log(parsedSettings);
  // Vypíše: { theme: 'dark', fontSize: 16, notifications: true }
}