How to count the number of certain objects in LocalStorage?

Good afternoon, in LocalStorage is stored several objects that can be divided into two groups: the first one is pair key comp-x, where * x is the numeric index and the second - cart-x (same story). Need to get two numbers - the number of elements with comp-x and the number of items from cart-x. How can I do that?
June 8th 19 at 17:18
1 answer
June 8th 19 at 17:20
Solution
Why not write an array with one key?
To work with an array would be much more convenient:
var cartItems = JSON.parse(localStorage.getItem('cart'));
var itemsQuantity = cartItems.length;
Maybe so, just can't figure out how best to implement it all. The fact is that the value of each key is also an object. And I don't really understand what (and how) nesting better to do. The point is that there are several blocks with buttons A and B. When you click on A localStorage key is added with the attribute of a button (attributes - it is just comp-x), and at a clique in B is added to the key attribute cart-x. And value of each such key is an object from multiple pairs. In the future you need to separate these two categories. How can I improve? Create two different object and in a condition to place them in certain categories? Then do not really understand how to create these objects is to place two empty object in the LocalStorage when you first download and then add to them? - Oleta96 commented on June 8th 19 at 17:23
well either object or array. At boot initialization:
var cart = JSON.parse(localStorage.getItem('cart')) || [];

And then, each time you add an item, overwrite the localStorage:
cart.push(element);
localStorage.setItem("cart", JSON.stringify(cart));


So the data will be loaded at boot if they are overwritten with each change. - Lenny.Botsfo commented on June 8th 19 at 17:26
Work great, thank you!) - Oleta96 commented on June 8th 19 at 17:29

Find more questions by tags JavaScriptjQuery