Ionic Storage update value which is object


#1

Hi, I’ve been looking for a while now in the forum, but can’t get it to work.

Basically I set my data using

    this.storage.set('data', [
      {id:1, name: 'a'}, {id: 2, name:'b'}
    ])

How do I edit the name of id:2 without overwriting the array? I’ve done some get and set but end up overwriting the entire object.

Hopefully I got some help. thanks.


#2

Simple solution with Array#Map:

const array = [{ id: 1, name: 'a' }, { id: 2, name: 'b' }];
const result = array.map(x => x.id === 2 ? ({ ...x, name: 'new name' }) : x);

#3

You can’t, not without rearranging the structure. You would have to store each little object under a separate key in order to do that.


#4

I got it to work with

this.storage.get('data').then(valueStr => {

  let value = valueStr;

   // Modify just that property
   value[1].name = "hahaha"; <--- need to specify index

   // Save the entire data again
   this.storage.set('pets', value);

   console.log(valueStr)
});

#5

I’m confused, because that still overwrites the entire array.