简体   繁体   中英

How to save array and object at once in localstorage?

var mara =  [{"name":"zach", "age":"27"}];    
var marathon2 = [{"ticketDetails" : [mara]}];
localStorage.setItem("ticket_marathon2",JSON.stringify($scope.ticket_marathon2));    
var details2 = JSON.parse( localStorage.getItem("ticket_marathon2") );    
console.log("data2",details2);

Try this:

var mara = [{"name":"zach", "age":"27"}];
var marathon2 = [{"ticketDetails" : mara}];

localStorage.setItem("ticket_marathon2",JSON.stringify(marathon2));

var details2 = JSON.parse( localStorage.getItem("ticket_marathon2") );

alert(JSON.stringify(details2[0].ticketDetails[0].name));
localStorage.setItem("ticket_marathon1", angular.toJson($scope.ticket_marathon1));

var details1 = angular.fromJson(localStorage.getItem("ticket_marathon1"));

Note: You dont need to inject $localStorage its a default html5 storage.

You can use

 $window.localStorage.setItem("ticket_marathon1",angular.toJson($scope.ticket_marathon1))

to store, var details1 =angular.fromJson($window.localStorage.getItem("ticket_marathon1")) to retrieve and $window.localStorage.removeItem("ticket_marathon1") to remove.Then you can access the values in any page and it is more flexible.

Note :Inject $window in your controller

You have var mara = [{"name":"zach", "age":"27"}]; - defined as an array with one object.

Afterwards: var marathon2 = [{"ticketDetails" : [mara]}];

stating that "ticketDetails" is an array with an array inside resulting in:

[{"ticketDetails": [[{"name":"zach"....}]]}] ?

Maybe remove [], unless it's intentional.

Another thing, try stringifying mara array as well, before adding it as the value of the object and stringifying it all together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM