David Hope
David Hope

Reputation: 1536

Javascript: removing object from array stored in localStorage?

I have an array stored in localStorage that looks like this:

[
  {
    "location": "westcliff, uk",
    "stopover": true
  },
  {
    "location": "westcliff, uk",
    "stopover": true
  },
  {
    "location": "southend, uk",
    "stopover": true
  },
  {
    "location": "Leigh-on-sea, uk",
    "stopover": true
  }
]

I have a button that when i click on, it will look for the localtion: in that array and it will delete that object from the array and then stores in the localstorage again.

The button code looks like this:

$(document).on('click', ".cart-del", function() {   
    var retrievedObject2 = localStorage.getItem('waypoints');
    var parsedObject2 = JSON.parse(retrievedObject2);
    var result2 = parsedObject2.filter(function(x){return x.location !== "westcliff, uk"; });
    var setLoc2 = JSON.stringify(result2);
    localStorage.setItem('waypoints', setLoc2);
}):

This all works fine.

The issue that i have is that when the button is clicked, it will remove every "westcliff, uk" object.

What i need to do is to only remove 1 object per click!

Could someone please advice on this issue?

Thanks in advance.

EDIT:

I tried this and this doesn't remove anything from the array:

    $(document).on('click', ".cart-del", function() { 

    var retrievedObject2 = localStorage.getItem('waypoints');
    var parsedObject2 = JSON.parse(retrievedObject2);

    for(var i = 0; i < parsedObject2.length; i++){
    if(parsedObject2[i].text == "westcliff, uk"){
    parsedObject2.splice(i, 1);
    break;
    }
    }



    var result2 = parsedObject2;    

    var setLoc2 = JSON.stringify(result2);
    localStorage.setItem('waypoints', setLoc2);
    }):

Upvotes: 0

Views: 513

Answers (2)

Murad Sofiyev
Murad Sofiyev

Reputation: 791

You can use find method instead of filter method

parsedObject2.find(function(x,e){
   if(x.location == "westcliff, uk")
     {
       return x.splice(e,1)
     }
 });

Upvotes: 0

Karl Reid
Karl Reid

Reputation: 2217

It's because you're using filter, there's no way to exit early so it may not be an appropriate tool for this use case. Instead you can just use a regular loop. Here's an example.

var a = [
  {text : "foo", n : 1 },
  {text : "foo", n : 2 }
];
for(var i = 0; i < a.length; i++){
  if(a[i].text == "foo"){
    a.splice(i, 1);
    break;
  }
}
console.log(a);

Or a neater approach using findIndex :

var a = [
  {text : "foo", n : 1 },
  {text : "foo", n : 2 }
];

a.findIndex((obj, i) => {
  if(obj.text === "foo"){
    a.splice(i,1);
    return true;
  }
});

console.log(a);

Upvotes: 1

Related Questions