Remove object key from localStorage object variable without removing from localStorage

Viewed 44

I need to remove object key from localStorage object variable without removing key from localStorage

let obj = localStorage;
let keys = Object.keys(localStorage).sort(function(a, b) {return a - b;});

for(let i = 0; i < keys.length; ++i){
    if (isNaN(keys[i])) {
        delete obj[keys[i]];
        keys.splice(i,1);
    }
}

code above removes non-numeric object key from obj variable, but also key is removing from localStorage

How to remove key from localStorage object variable and keep that key in localStorage?

2 Answers

What you’re doing here is you’re copying the reference of the localStorage object and working on the localStorage itself What you can do is instead of getting localStorage like this:

const obj = localStorage;

Do like this:

const obj = {...localStorage};

So what you’re doing here you’re copying the object by value and not by reference

Problem solved by using Object.values(localStorage) and obj.slice(i,1) instead of "delete" now i can safe remove keys from obj variable without removing localStorage keys and can get obj.length too.

let obj = Object.values(localStorage),
keys   = Object.keys(localStorage).sort(function(a, b) {return a - b;});
for(let i = 0; i < keys.length; ++i){
    if (isNaN(keys[i])) {
        keys.splice(i,1);
        obj.splice(i,1);
    }
}
Related