0

I have a local storage item as per below

(2) [{…}, {…}]
0
:
cityName
:
"durban"
__proto__
:
Object
1
:
cityName
:
"cape town"
__proto__
:
Object

I would like to delete 1 item only, based on whether the cityName matches the local storage item i.e if the user clicks "durban" then delete durban.

I already am able to get the name from the click

  deleteCity(event){
    var target = event.currentTarget.id;
    console.log(target);
    var getLSCityName = localStorage.getItem('savedLocations');
    var getLSCityNameArr = JSON.parse(getLSCityName);

      for(var i = 0; i < getLSCityNameArr.length; i++){
        if (getLSCityNameArr[i].cityName == target){
          getLSCityNameArr.splice[i].cityName;
          localStorage.setItem('savedLocations', JSON.stringify(getLSCityNameArr));
        }
      } 
    }
3
  • after you "do something here", you'll need to, a) JSON.stringify it, then b) write it back to localStorage - if the savedLocations represents an array, then use array filter method to remove the desired item Commented Feb 20, 2018 at 5:53
  • what is the 'local storage'? Is it an array? object? Commented Feb 20, 2018 at 5:56
  • it is an array. I have updated my attempt Commented Feb 20, 2018 at 5:59

1 Answer 1

2
please try like this

function deleteItem(index){
            var getLSCityName = localStorage.getItem('savedLocations');
            getLSCityName.splice(index,1); // delete item at index
        }
Sign up to request clarification or add additional context in comments.

1 Comment

ok this works deleteCity(event){ var target = event.currentTarget.id; var getLSCityName = localStorage.getItem('savedLocations'); var getLSCityNameArr = JSON.parse(getLSCityName); for(var i = 0; i < getLSCityNameArr.length; i++){ if (getLSCityNameArr[i].cityName == target){ getLSCityNameArr.splice(i, 1); localStorage.setItem('savedLocations', JSON.stringify(getLSCityNameArr)); } } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.