Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove object key from localStorage object variable without removing from localStorage

Tags:

javascript

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?

like image 885
redevil Avatar asked Aug 06 '26 04:08

redevil


1 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

like image 156
EkkoKo Avatar answered Aug 07 '26 19:08

EkkoKo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!