从本地JSON文件中删除项目-JSON对象

时间:2019-01-24 21:41:09

标签: javascript json

JSON文件包含以下内容:

{
  "pets": [
    {
      "id": 1,
      "name": "Hanna",
      "speciesId": 2,
      "sex": "f",
      "age": 4
    },
    {
      "id": 2,
      "name": "Chris",
      "speciesId": 1,
      "sex": "m",
      "age": 5
    }
  ]
}

在这里我获取JSON数据,然后进行字符串化并设置为sessionStorage。

$.getJSON("/src/data/pets.json", function(json) {
  let petsData = JSON.stringify(json);

  window.sessionStorage.setItem("json", petsData);
});

然后我将其获取并将其解析回JSON,以便在整个应用程序中使用。

let theDataStr = window.sessionStorage.getItem("json");
let theData = JSON.parse(theDataStr);

我想删除包含值“ Hanna”的整个项目,并尝试了以下操作:

  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);
    }
  }

这很好,直到我回过头来查看会话存储并得到以下信息:

Image of JSON in Web Inspector

为什么该项目保留0索引,现在为空?

此外,当我随后尝试使用该数据时,由于以下项目不再存在speciesId,我收到以下JS控制台错误:

Uncaught TypeError: Cannot read property 'speciesId' of undefined
    at HTMLButtonElement.<anonymous>

编辑:使用接头:

  var newData = theData.pets[index];

  newData.splice(index, 1);

  let petsData = JSON.stringify(newData);

  window.sessionStorage.setItem("json", petsData);

返回以下错误:

Uncaught TypeError: newData.splice is not a function
    at HTMLInputElement.<anonymous>

0 个答案:

没有答案
相关问题