简体   繁体   English

如何通过JSON在本地存储中存储包含数组对象的对象

[英]How to store an Object containing Array-Objects in local Storage By JSON

I have this Object containing pretty much anything i want to know about a workout. 我有这个对象,其中包含我想了解的几乎所有锻炼内容。 Yet when I Stringify the object the array-objects aren't stored or something. 但是,当我将对象字符串化时,不会存储数组对象或其他东西。

This is my object i want to stringify: 这是我要分类的对象:

Object {name: "testWorkout", program: Array[4]}
name: "testWorkout"
program: Array[4]
        first: Array[3]
        slope: 0
        speed: "medium"
        time: 10
        length: 3
        __proto__: Array[0]

        interval1: Array[4]
        radio: "Time"
        size: "33"
        slope: "79"
        speed: "fast"
        length: 4
        __proto__: Array[0]

        interval2: Array[4]
        radio: "Time"
        size: "3322"
        slope: "16"
        speed: "medium"
        length: 4
        __proto__: Array[0]

        last: Array[3]
        slope: 0
        speed: "medium"
        time: 20
        length: 3

    __proto__: Array[0]
    length: 4
    __proto__: Array[0]
__proto__: Object

But instead it stringifies nice it does stringify as: 但是相反,它很好地将其字符串化为:

{"name":"testesr","program":[null,null,null,null]} 

How to solve this with pure JavaScript? 如何用纯JavaScript解决这个问题? So without JQuery? 那么没有JQuery吗?

These are my stringify and read method: 这些是我的stringify和read方法:

function putInLocalStorage(){
    console.log(JSON.stringify(workout));
    localStorage.setItem('workout-'+workout.name, JSON.stringify(workout));
}

function readLocalStorage(){
    var retrievedObject = localStorage.getItem('workout-'+workout.name);
    console.log('retrievedObject: ', JSON.parse(retrievedObject));    
}

change your object looking as below then stringify. 如下所示更改对象,然后进行字符串化。 It should work. 它应该工作。

Object {name: "testWorkout", program: {}}

Point here is normal JavaScript arrays are designed to hold data with numeric indexes. 这里要JavaScript是,普通的JavaScript数组旨在容纳带有数字索引的数据。 You can stuff named keys on to them but the JSON array data type cannot have named keys on an array. 您可以在其上填充命名键,但是JSON数组数据类型不能在数组上具有命名键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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