The JSON file contains the following:
{
"pets": [
{
"id": 1,
"name": "Hanna",
"speciesId": 2,
"sex": "f",
"age": 4
},
{
"id": 2,
"name": "Chris",
"speciesId": 1,
"sex": "m",
"age": 5
}
]
}
Here's where I get the JSON data and then stringify and set into sessionStorage.
$.getJSON("/src/data/pets.json", function(json) {
let petsData = JSON.stringify(json);
window.sessionStorage.setItem("json", petsData);
});
I then get it and parse it back into JSON for use throughout application.
let theDataStr = window.sessionStorage.getItem("json");
let theData = JSON.parse(theDataStr);
I want to delete the entire item that contains the valued 'Hanna' and have tried the following:
let PetToDelete = document.getElementById("PetNames").value // This will be the 'Hanna';
for (let index = 0; index < theData.pets.length; index++) {
console.log(theData.pets[index]);
if (PetToDelete == theData.pets[index].name) {
delete theData.pets[index];
let petsData = JSON.stringify(theData);
window.sessionStorage.setItem("json", petsData);
}
}
This works fine until I look back at the Session Storage and I get this:
Why is the item retaining the 0 index and is now null?
Furthermore, when I then try to use that data, I get the following JS Console Error because speciesId doesn't exist for that item anymore:
Uncaught TypeError: Cannot read property 'speciesId' of undefined
at HTMLButtonElement.<anonymous>
Edit: Using Splice:
var newData = theData.pets[index];
newData.splice(index, 1);
let petsData = JSON.stringify(newData);
window.sessionStorage.setItem("json", petsData);
returns the following error:
Uncaught TypeError: newData.splice is not a function
at HTMLInputElement.<anonymous>