如何在localstorage中一次保存数组和对象?

时间:2017-06-02 06:12:34

标签: javascript angularjs arrays

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);

4 个答案:

答案 0 :(得分:0)

试试这个:

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));

答案 1 :(得分:0)

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

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

注意:您不需要将$ localStorage注入其默认的html5存储空间。

答案 2 :(得分:0)

您可以使用

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

存储, var details1 =angular.fromJson($window.localStorage.getItem("ticket_marathon1"))要检索并$window.localStorage.removeItem("ticket_marathon1")删除。然后您可以访问任何页面中的值,并且更灵活。

注意:在控制器中注入$ window

答案 3 :(得分:0)

您有var mara = [{"name":"zach", "age":"27"}]; - 定义为包含一个对象的数组。

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

声明“ticketDetails”是一个内部有数组的数组,结果是:

[{“ticketDetails”:[[{“name”:“zach”....}]]}]?

除非是故意的,否则可以删除[]。

另外,在将mara数组添加为对象的值并将其全部字符串化之前,请尝试对mara数组进行字符串化。