1

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);
2
  • So your question is how to append? Can you post what you have tried so far? Commented Jun 20, 2016 at 21:23
  • First of all I don't think you want to have two identical keys (items) in the same ison object. Commented Jun 20, 2016 at 21:34

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

It is nearly the same answer as mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.