Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - localStorage array of objects handling

Array of JSON objects are stored in HTML5 localStorage.
For now delimiter is ;
For accessing and modifying array of objects from localStorage, split(';') and join(';') operations used.

However ,delimiter approach looks unstable.
For instance ; could be met inside objects attribute and split(';') operation will be uncorrect.

It could be used ;; for delimiter,but i'm not certain it will be stable also.

Is there any robust way to handle localStorage presented as array of objects,as far localStorage saved as String?

EDIT

one of stoppers is that array of object couldn't be saved to localStorage as classical: "[{},{}]"
localStorage converts it automatially to String like "{},{}"

my current data within localStorage:

"{"name":"volvo","id":"033"};{"name":"saab","id":"034"}"

assumption
perhaps,i can add [ at the start and ] at the end,but it looks not gracefull

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just convert the objects to JSON strings:

localStorage.setItem("savedData", JSON.stringify(objects));

And vice versa:

objects = JSON.parse(localStorage.getItem("savedData")));

Or you can add multiple objects in the same localStorage value:

localStorage.setItem("savedData", JSON.stringify([object1, object2 /*, etc*/]));
object1 = JSON.parse(localStorage.getItem("savedData"))[0];
object2 = JSON.parse(localStorage.getItem("savedData"))[1];

Here's the DOM storage specification.

You can also access savedData like this:

localStorage.savedData = "Hello world"
var foo = localStorage.savedData;

This can be used for both getting and setting the data, but it is considered less "safe" than getItem('name'); and setItem('name', 'value');


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...