Search code examples
javascriptlocal-storagestringify

Why cannot I JSON.stringify localStorage


I tried this one

JSON.stringify(localStorage, function(key, value) {
        console.log(key);
        return (key.split('.')[0] === 'SUWDdb') ? value : undefined;
})

and it only returns undefined, console only log one entries. can any one give me a reason and a solution?


Solution

  • Well, nothing at the top level satisfies your condition, and in that case your function is returning undefined, which means nothing below that is stringified. You probably want:

    JSON.stringify(localStorage, function(key, value) {
        console.log(key);
        return (typeof value === 'object' || key.split('.')[0] === 'SUWDdb') ? value : undefined;
                ^^^^^^^^^^^^^^^^^^^^^^^^^
    })
    

    This will allow JSON.stringify to keep traversing downward when it encounters an object.