在jquery和javascript中删除json数组中的所有元素

时间:2015-12-17 05:12:42

标签: jquery arrays json

我正在研究一种可以删除“Bottin”中所有数组内容的方法。 数据以名为“数据”的密钥存储在计算机的LocalStorage中。

这是我的Json样本:

function delAllBottin() {
    bd = localStorage.getItem('data');      
    var descJsonObjects = bd.Bottin;
    bd.Bottin.splice(0, descJsonObjects.length);    
}

这是我的部分解决方案:

{{1}}

现在似乎不起作用,我不知道我在这里缺少什么...

3 个答案:

答案 0 :(得分:1)

1将localStorage中的字符串解析为JSON

2删除您不想要的项目(使用切片())

3将JSON设为字符串

4在localStorage中重新设置

var items = JSON.parse(localStorage.getItem("data")); // updated
   for (var i =0; i< items.length; i++) {
        var items = JSON.parse(items[i]);

            items.splice(i, 1);

    }
    item = JSON.stringify(items);
    localStorage.setItem("data", items);

答案 1 :(得分:1)

您无法将对象设置为localStorage / sessionStorage的值。在从存储中获取JSON之后,您需要将其设置为JSON字符串。

设置时

var data = {.....}; //Build your data object
localStorage.setItem('data', JSON.stringify(data));

获取(和编辑)

var jsonData = localStorage.getItem('data');
var data = JSON.parse(jsonData);
//If you want to do any modification, do it now
//then set it back to the storage
localStorage.setItem('data', JSON.stringify(data));

答案 2 :(得分:1)

首先,以字符串格式存储json对象,如:

var data = {
    "descriptions": [
        {
            "Fabricant": "Test",
            "Produit": "Test",
            "Prix": "11.11",
            "Details": " asdfasd",
            "Categorie": "Categorie_Baseball",
            "Images": "Hockey_Article_01.jpg"
        },{
            "Fabricant": "Test",
            "Produit": "Test",
            "Prix": "11.11",
            "Details": " asdfasd",
            "Categorie": "Categorie_Baseball",
            "Images": "Hockey_Article_01.jpg"
        },{
            "Fabricant": "Test",
            "Produit": "Test",
            "Prix": "11.11",
            "Details": " asdfasd",
            "Categorie": "Categorie_Baseball",
            "Images": "Hockey_Article_01.jpg"
        }
    ],
    "Bottin": [
        {
            "Nom": "Andy",
            "Prenom": "Matador",
            "Fonction": "dtesasd",
            "Courriel": "cyd@vde.ca",
            "Telephone": "515-555-5555"
        }, {
            "Nom": "Andy",
            "Prenom": "Matador",
            "Fonction": "dtesasd",
            "Courriel": "cyd@vde.ca",
            "Telephone": "515-555-5555"
        },{
            "Nom": "Andy",
            "Prenom": "Matador",
            "Fonction": "dtesasd",
            "Courriel": "cyd@vde.ca",
            "Telephone": "515-555-5555"
        }
    ],
    "users": {
        "admin": "Inf2005"
    }
}

localStorage.setItem("data", JSON.stringify(data));

现在,从中清除Bottin数组:

var data = JSON.parse(localStorage.getItem("data"));
data.Bottin = []; // array cleared

现在,再次保存:

localStorage.setItem("data", JSON.stringify(data));