Search code examples
angulartypescriptionic-frameworkionic2ionic3

Update part of object in Ionic Storage key/value pair


I have an Ionic Storage DB with the following key/value pair:

Key: settingsJSON Value: {toggleDates: false, toggleIndicator: false, toggleRepayments: false}

Is there any way to update part of the object (i.e set toggleDates to true) without overriding the rest of object stored in the value?

I've tried:

 let settingsTemp = JSON.stringify({toggleDates: true});
 this.storage.set('settingsJSON', settingsTemp)

But this updates the entire object to {toggleDates: true}.

I've also tried:

this.storage.set('settingsJSON.toggleDates', true)

But this just creates a new key/value named settingsJSON.toggleDates.


Solution

  • What about something like this:

    // Get the entire data
    this.storage.get('settingsJSON').then(valueStr => {
        let value = valueStr ? JSON.parse(valueStr) : {};
    
         // Modify just that property
         value.toggleDates = true;
    
         // Save the entire data again
         this.storage.set('settingsJSON', JSON.stringify(value));
    });