удаление из localStorage на клик

Дано: пользователь кликает на свитчер чтобы добавить в избранное монету. Не получается удалить из localStorage (если пользователь возвращается свитчер в режим off). Пробую команду "localStorage.removeItem("checkedCoins")", но он удаляет все (как clear())

function switchClick(event) {

    if(event.target.checked){
        let coinId = event.currentTarget.id;
        const jsonString = localStorage.getItem("checkedCoins")
        if (jsonString) {
                let cryptoCoins = JSON.parse(jsonString)
                cryptoCoins.push({id: coinId});
                let checkedCoinsString = JSON.stringify(cryptoCoins);
                localStorage.setItem("checkedCoins", checkedCoinsString);  
                
                if(cryptoCoins.length > 6 ) {
                    alert("delete")
                }
        } else {
            localStorage.setItem("checkedCoins", JSON.stringify([{id: coinId}]));  
        }
     } else {

       localStorage.removeItem("checkedCoins");
     }
    }

Ответы (1 шт):

Автор решения: Pavel Nazarian

Сделал с массивом, так по-моему проще, если кроме id ничего не пишете

function switchClick(event) {  
  let coinId = +event.currentTarget.id;  
  const cryptoCoins = JSON.parse(localStorage.getItem("checkedCoins"));    
  if (event.target.checked) {            
    if (cryptoCoins === null) {          
      localStorage.setItem("checkedCoins", JSON.stringify([coinId]));      
      return
    }
    if (cryptoCoins.includes(coinId)) return
    cryptoCoins.push(coinId)    
    localStorage.setItem("checkedCoins",JSON.stringify(cryptoCoins));       
    return
  }
  let filtered_cryptoCoins = cryptoCoins.filter(item => item !== coinId)    
  if (filtered_cryptoCoins.length === 0) {
    localStorage.removeItem("checkedCoins");
    return
  }
  localStorage.setItem("checkedCoins",JSON.stringify(filtered_cryptoCoins));  
}
→ Ссылка