bsh
bsh

Reputation: 447

delete an object from an array of objects in local storage javascript

I have an array of objects in local storage like this:

ios = [{
    "id" : 1,
    "type" : "in",
    "cat" : "Diversi",
    "qty" : 50,
    "date" : "2016-11-02T09:51:48.872Z",
    "descr" : ""
  }, {
    "id" : 1,
    "type" : "in",
    "cat" : "Lavoro",
    "qty" : 50,
    "date" : "2016-11-02T10:08:11.362Z",
    "descr" : ""
  }];

I want to delete one of the objects with this function:

function remove(io) {
    var ios = localStorage.getItem('ios') ? JSON.parse(localStorage.getItem('ios')) : [];
    var index;
    for (var i = 0; i < ios.length; i++) {
        if (ios[i] === io) {
          index=i;
          break;
        }
    }
    ios.splice(index, 1);
    localStorage.setItem('ios', JSON.stringify(ios));
}

But when i call the function, and pass it the parameter to delete, it doesn't delete the one I want, but the first one in local storage instead. Can anyone help me please?

Upvotes: 0

Views: 2238

Answers (3)

TaoR
TaoR

Reputation: 51

You can't test 2 objects being equal by using ===. Try to use this function:

function isEquivalent(a, b) {
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);

    if (aProps.length != bProps.length) {
        return false;
    }

    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];

        if (a[propName] !== b[propName]) {
            return false;
        }
    }

    return true;
}

And instead ios[i] === io, you call isEquivalent(ios[i],io).

Upvotes: 1

mpsbhat
mpsbhat

Reputation: 2773

You can use map function as,

function removeItem() {    
  var ios = JSON.parse(localStorage.getItem('ios'));
  var index = ios.map(function(element) {
    return element.cat;
  }).indexOf(io.cat);
  ios.splice(index, 1);
  localStorage.setItem('ios', JSON.stringify(ios));
}

to remove item based on passed object's cat in the array. Sample

Upvotes: 0

Gaurav joshi
Gaurav joshi

Reputation: 1799

This is because your condition never get satisfied, so your index variable is always undefined ... So either pass some unique key value in the object like "id" and compare that key value pair like :-

function remove(id) {
    var ios = localStorage.getItem('ios') ? JSON.parse(localStorage.getItem('ios')) : [];
    var index;
    for (var i = 0; i < ios.length; i++) {
        if (ios[i].id === id) {
          index=i;
          break;
        }
    }
    if(index === undefined) return 
    ios.splice(index, 1);
    localStorage.setItem('ios', JSON.stringify(ios));
}

OR

use some third party like LODASH Doc as:-

function remove(io) {
        var ios = localStorage.getItem('ios') ? JSON.parse(localStorage.getItem('ios')) : [];
        var index;
        index = _.findIndex(ios , io);
        if(index === -1) return 
        ios.splice(index, 1);
        localStorage.setItem('ios', JSON.stringify(ios));
    }

Upvotes: 1

Related Questions