0

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:

Image of JSON in Web Inspector

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>
Jamie Bohanna
  • 417
  • 1
  • 3
  • 19
  • 1
    The fact that you start with JSON is completely 100% irrelevant. JSON is just a serialization format for moving data between systems. Don't try to manipulate JSON itself. – Brad Jan 24 '19 at 21:46
  • take a look at this answer https://stackoverflow.com/a/500617/5927361 – Kisinga Jan 24 '19 at 21:48
  • "pets" is an array, not an object. Try `x=[1,2,3,4]; delete x[2]`. What is the result you expect? Should there be a gap in the array (what you're observing) or should the elements after `2` be shifted down? – mpen Jan 24 '19 at 21:48
  • @mpen I'd want the results to be shifted down as if '2' never existed, so [1, 3, 4] – Jamie Bohanna Jan 24 '19 at 21:49
  • 1
    @JamieBohanna — See the duplicate – Quentin Jan 24 '19 at 21:52
  • 1
    Re edit: Look at the duplicate more carefully. Think about the difference between the array you want to delete something from and the thing you want to delete from it. – Quentin Jan 24 '19 at 21:54
  • @Quentin - Just figured out what I was doing thanks to your comment. Thank you! <3 – Jamie Bohanna Jan 24 '19 at 22:02

0 Answers0