Alko
Alko

Reputation: 1439

JavaScript, jQuery, Localstorage append items to an array

Is it possible to do something like this:

var id = 1;
var data = {
    items: {
        id: id,
        html: '<p> Hello</p>',
    }
};

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

them later on I want to keep the existing values of data.items and append a new array to it like:

var id = 2;
var data = {
    items: {
        id: id,
        html: '<p> Hello 2</p>',
    }
};

so that the final result would look like:

var data = {
    items: {
        id: 1,
        html: '<p> Hello 1</p>',
    },
    items: {
        id: 2,
        html: '<p> Hello 2</p>',
    }
};

then I can get it:

var result = JSON.parse(localStorage.getItem("demoitems"));

$.each(result.items, function(k, v) {
... do loop here
});

I have tried something like this:

    var newdata = {
        items: {
            id: 2,
            html: '<p> Hello 2</p>',
        }
    };

var olddata = JSON.parse(localStorage.getItem("demoitems"));
newdata.push(newdata, olddata);

Upvotes: 1

Views: 1715

Answers (2)

KIMB-technologies
KIMB-technologies

Reputation: 889

You can't push to Objects, use an Array instead. And the index in an Object must be unique.

var olddata = [
    {
        id: 2,
        html: '<p> Hello 2</p>'
    }
];

localStorage.setItem("demoitems", JSON.stringify(olddata))

var newdata = {
        id: 2,
        html: '<p> Hello 2</p>'
};

var data = JSON.parse(localStorage.getItem("demoitems"));
data.push(newdata);
localStorage.setItem("demoitems", JSON.stringify(data))

alert( localStorage.getItem("demoitems") );

Try it here: https://jsfiddle.net/snht4kvy/

Upvotes: 1

Kairat
Kairat

Reputation: 800

First of all you don't want to have two identical keys (items) in the same json object. What you can do is, add your item objects to the array in the json object

var id = 1;
var data = {
    // array of items
    items: [{
        id: id,
        html: '<p> Hello</p>',
    }]
};
localStorage.setItem("demoitems", JSON.stringify(data));

Then you can add new items to the array like so:

var newitem = {
    id: 2,
    html: '<p> Hello 2</p>',
};

var olddata = JSON.parse(localStorage.getItem("demoitems"));
olddata["items"].push(newitem);
// store the data
localStorage.setItem("demoitems", JSON.stringify(olddata));

Upvotes: 0

Related Questions