Вопрос

Sorry if this has been answered elsewhere here, I have not found it if it has been. I have valid JSON:

{
    "main": [
        {
            "Example1": [
                {
                    "Example1_Var02": "5",
                    "Example1_Var09": "443",
                    "Example1_Var27": "23",
                    "Example1_Var01": "31"
                }
            ],
            "Example2": [
                {
                    "Example2_Var99": "2",
                    "Example2_Var84": "344",
                    "Example2_Var46": "56",
                    "Example2_Var03": "78"
                }
            ]
        }
    ]
}

whose names are unknown to me and/or will change regularly, except for the super key of "main." Assuming a successful $.ajax() call that returns "data," e.g. success: function(data) { , I would like to break out each nested array into localstorage without needing to know their key names, as I may never know them. But as it is, I cannot get something where I know those sub-array names to work. This:

for(var key in data){
   localStorage.setItem(key, JSON.stringify(data[key]));
}

will create a single localstorage instance of "main". But this (and other variations):

for(var key in data){
   localStorage.setItem(key.Example1[0], JSON.stringify(data[key.Example1]));
}   

returns an error "Uncaught TypeError: Cannot read property '0' of undefined". And since I cannot accomplish this with a known subarray key name, doing it at an abstract, anonymous level is more challenging still. How can I simply output whatever nested arrays happen to be contained in "main" to separate local storage without necessarily knowing their names in the JSON? Thanks for your help.

Это было полезно?

Решение

As @Pointy pointed out, if you can always expect main to be there and the structure of the object is predictable (even if the names and data aren't) you can use a for...in statement to iterate over the object:

for(var outer in x.main){ 
    for(var inner_key in x.main[outer]){ 
        localStorage.setItem(inner_key, JSON.stringify(x.main[outer][inner_key]));

    }
}

console.log(localStorage.getItem('Example1'));
// "[{"Example1_Var02":"5","Example1_Var09":"443","Example1_Var27":"23","Example1_Var01":"31"}]"
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top