Home > Blockchain >  how to change properties of complex objects in local storage js
how to change properties of complex objects in local storage js

Time:01-18

let obj = [
           {
            'frontend':['link1','link2']
           },
           {
            'backend':['link1','link2']
           }
          ]

localStorage.setItem('tutorial',JSON.stringfy(obj));

i want to change the value of link1 to something else i have tried the following method but i want to know that is there a better way

let x=JSON.parse(localStorage.tutorial);
x[0]['front-end'][0]='10';
localStorage.setItem('tutorial',JSON.stringify(x));

CodePudding user response:

There isn't a "better" way to directly modify localStorage that uses less resources or space. Therefore, if performance is critical to you, you should minimize how often you read from and write to localStorage.

For instance, to minimize reads, it's probably only necessary to read a value from localStorage once, the first time you need it for something. After parsing it, you have a copy of the value in JavaScript memory, so if it needs to change, you can modify the value directly.

And to minimize writes, you should only write the value back to localStorage when you are absolutely sure you want it saved. So, that can be done continuously whenever the value changes, or you can give the user an explicit save button and let them choose when they want to write the changes to localStorage.

CodePudding user response:

Instead of performing two localStorage setItem operation, You can do it once after updating the values and for that no need to create any temp variable. You can update the values by using Array.forEach() method.

Live Demo :

let obj = [
  {
    'frontend':['link1','link2']
  },
  {
    'backend':['link1','link2']
  }
];

obj.forEach(item => {
    Object.values(item).forEach(val => {
    val[0] = '10'
  })
});

console.log(obj);

// localStorage.setItem('tutorial',JSON.stringify(obj));

  • Related