Properties that cannot be accessed after filling an object into a window.localStorage?

window.localStorage.setItem("obj", {name: "hhh", age: 100});

localStorage.obj exists, but localStorage.obj.name is undefined.

could you tell me how to access the value? of name?

Mar.02,2021

localStorage considerations

normally we store JSON in localStorage, but in localStorage we automatically convert localStorage to string form

at this point, we can use the JSON.stringify () method to convert JSON into a JSON string

.

example:

if(!window.localStorage){
    alert("localstorage");
}else{
    var storage=window.localStorage;
    var data={
        name:'luozz',
        sex:'man',
        hobby:'program'
    };
    var d=JSON.stringify(data);
    storage.setItem("data",d);
    console.log(storage.data);
}
 

to convert the JSON string into a JSON object after reading, use the JSON.parse () method

var storage=window.localStorage;
var data={
    name:'luozz',
    sex:'man',
    hobby:'program'
};
var d=JSON.stringify(data);
storage.setItem("data",d);
//JSONJSON
var json=storage.getItem("data");
var jsonObj=JSON.parse(json);
console.log(typeof jsonObj);
print out Object object

another thing to note is that other types should be converted as well.


localStorage saves the string
you need to convert it to JSON string first, and then save
to get it, first convert it to object


 var obj = {"a": 1,"b": 2}; 

 obj = JSON.stringify(obj); 

 window.localStorage.setItem("temp2", obj);//{"a":1,"b":2};

 obj=JSON.parse(window.localStorage.getItem("temp2"));

thanks for the invitation. You can try the following code. If you store an object, you need to perform a wave of conversion storage: object-"string; take: string -" object

let obj = {name: 'hhh', age: 100};
window.localStorage.setItem('obj', JSON.stringify(obj));

let getObj = JSON.parse(window.localStorage.getItem('obj'));

localStorage saves only strings.


localStorage and sessionStorage can only store strings. JSON.stringify is needed when saving objects, and JSON.parse is required when fetching.


localStorage can only save strings,
so when you pass in an object, you will automatically call the object's toString () ,
so you print localStorage.obj
and you will find that the result is [object Object] string

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1ea891d-1ee8.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1ea891d-1ee8.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?