Ismailp
Ismailp

Reputation: 2383

Adding value to localStorage

I'm trying to add a value to a key in HTML5 localStorage.

Here is my code:

    var splice_string = [];
    splice_string += "Test value";
    var original = JSON.parse(localStorage.getItem('product_1'));
    original['spliced'] = JSON.stringify(splice_string);

This doesn't seem to work because when I check the localStorage the original['spliced'] is empty.

What am I doing wrong here?

Thanks!

Upvotes: 2

Views: 8729

Answers (1)

raina77ow
raina77ow

Reputation: 106483

You're probably looking for this:

var splice_string = 'Test Value',
    original = JSON.parse(localStorage.getItem('product_1'));

// you might want to add checking for existence here, with something like...
// if (original === null) original = {};

original['spliced'] = splice_string;
localStorage.setItem('product_1', JSON.stringify(original));

In the code you've shown not only splice_string contains something that's not a string, but you don't actually store the updated value of original in localStorage.

Upvotes: 2

Related Questions