Search code examples
javascriptarraysionic2ionic-storage

Removing an element form an array Ionic 2 Storage


I have set the array of data into the storage with the key 'todo' in the data provider as

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

@Injectable()
export class DataProvider {

  constructor(public storage: Storage) {
    console.log('Hello DataProvider Provider');
  }

  getData() {
    return this.storage.get('todos'); 
  }

  save(data){
    this.storage.set('todos', data);
  }

  remove(id){
    console.log("Removing data ID:",id);
    this.storage.remove(id);
  }


}

The data consists of an array with properties id, title, body as

{ id: 0, title: "lorem epsum", body: "lorem epsum" }
{ id: 1, title: "lorem epsum", body: "lorem epsum" }
{ id: 2, title: "lorem epsum", body: "lorem epsum" }
{ id: 3, title: "lorem epsum", body: "lorem epsum" }
{ id: 4, title: "lorem epsum", body: "lorem epsum" }

Now, what i am trying to do is to remove the array from the data. I want to remove an array with id 3

{ id: 3, title: "lorem epsum", body: "lorem epsum" }

I have used the storage function remove(key) to remove one array

But it is showing the error like

3 used as a key, but it is not a string.

I want to try with the title but the title of the item may not be unique. SO, i tried to remove the array using the id.

Any help will be appreciated.

Thank you.


Solution

  • Use this.storage.remove(key).The Key is the ID of the array element in the storage