Michael Lee Michael Lee - 1 month ago 6
Javascript Question

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?

Answer

Well, nothing at the top level satisfies your condition, and 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.

Comments