Reputation: 1439
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
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
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