S
S
Shane Matte2016-05-15 13:30:04
JavaScript
Shane Matte, 2016-05-15 13:30:04

Why does it say underfined when using data from localstorage?

I put json in localstorage, select json key into a variable, writes underfined. I can't understand why. If I write this json directly directly to a variable, the selection works, but it doesn’t want to from localstorage. What is the problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Ineshin, 2016-05-15
@mattedev

Here is an example of how to do it right: https://jsfiddle.net/IonDen/1hkzvopy/

var testObject = {
    a: 10,
    b: 20,
    c: 30
}

// неправильно!
localStorage.setItem("test", testObject);
var newObject = localStorage.getItem("test");
console.log(newObject.a); // undefined

// Нужно не забывать превращать в строку и обратно!
localStorage.setItem("test2", JSON.stringify(testObject));
var newObject2 = JSON.parse(localStorage.getItem("test2"));
console.log(newObject2.a) // 10

P
Peter, 2016-05-15
@petermzg

What do you mean by "put json"?
LocalStorage can only store strings.

D
Dmitry Eremin, 2016-05-15
@EreminD

it’s not clear without the code, but maybe it’s worth trying to take from localstorage and do it first JSON.parse(//данные из localstorage);
But still, you need to look at the code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question