Anil Sagar
Posts: 0
Joined: Fri Jul 04, 2014 1:13 pm

How to push a multi key and value record to a localStorage array

I have a local storage array Packs_LS as:

[{"pack":"10 SMS free with Rs. 200 SMS pack","image":"","price":"20"},{"pack":"2 GB free with 6GB pack for Rs. 400","image":"","price":"30"}]

Now I want to add following values from localStorage to it as a record:

pack_local="3 GB free with 10 GB pack for Rs. 1000";

image_local="imageA.png";

price_local="20"

The updated Packs_LS array should look like:

[{"pack":"10 SMS free with Rs. 200 SMS pack","image":"","price":"20"},{"pack":"2 GB free with 6GB pack for Rs. 400","image":"","price":"30"},{"pack":"3 GB free with 10 GB pack for Rs. 1000","image":"imageA.png","price":"20"}]

Currently I am trying to solve it by using the following code but it doesn't seem to work. It appends an empty array like [] at the end of Packs_LS.

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

var pack_array = [];

pack_array.pack=localStorage.getItem("pack_local");

pack_array.image=localStorage.getItem("imageName_local");

pack_array.price=localStorage.getItem("price_local");

var Packs_LS_obj = JSON.parse(localStorage.getItem( "Packs_LS" ));

Packs_LS_obj.push(pack_array);

localStorage.setItem( "Packs_LS", JSON.stringify(Packs_LS_obj) );

All the above code is placed in success event of a read service where I fetch info for Packs_LS from a DB array.

Maryna Brodina
Posts: 0
Joined: Thu Apr 05, 2012 7:27 am

How to push a multi key and value record to a localStorage array

Hello!

Please use the following code:
prevar arr = JSON.parse(localStorage.getItem("Packs_LS"));

var obj = {};
obj.pack = "3 GB free with 10 GB pack for Rs. 1000";
obj.image = "imageA.png";
obj.price = "20"
arr.push(obj);
localStorage.setItem("Packs_LS", JSON.stringify(arr));/pre

Anil Sagar
Posts: 0
Joined: Fri Jul 04, 2014 1:13 pm

How to push a multi key and value record to a localStorage array

Many thanks Maryna. So the only change that I had to make in my code above was to replace [] with {}...:-)

Maryna Brodina
Posts: 0
Joined: Thu Apr 05, 2012 7:27 am

How to push a multi key and value record to a localStorage array

Hello!

Yes, pack_array should be an object not array.

Return to “Issues”