Link to home
Start Free TrialLog in
Avatar of dev09
dev09

asked on

localStorage - get values

Hi all,

I have 'localStorage' data from an existing website cart that is displaying in the following format:

{"SCI-1":{"quantity":1,"id":"SCI-1","price":50,"name":"ABC","cbm":"0.000001","weight":"0.1"},"SCI-2":{"quantity":1,"id":"SCI-2","price":100,"name":"DEF","cbm":"0.000001","weight":"0.1"},"SCI-3":{"quantity":1,"id":"SCI-3","price":50,"name":"GHI","cbm":"0.000001","weight":"0.1"}}

Open in new window


I used this code to give me the above:
var result = localStorage["cartData"];
console.log(result);

Open in new window


How do i go about extracting the item totals of:
- quantity
- cbm (cubic meters)
- weight

I know it will need to loop through the localStorage but just not sure how too.
Anyone got some experience with this and a super easy solution?

Thanks a heap!!
Avatar of Snarf0001
Snarf0001
Flag of Canada image

You should call JSON.parse first once you have the value from storage, to turn it into a valid object.
Then looping throw the first level of associative properties, and getting direct .quantity values from those objects.

Something like this:

var totalQty = 0, totalWeight = 0.0;
var result = JSON.parse(localStorage["cartData"];
for(var sci in result) {
	totalQty += sci.quantity;
	totalWeight += sci.weight;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of mankowitz
mankowitz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dev09
dev09

ASKER

Perfect, thanks!!