最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Localstorage: Count how many values in key when using stringify - Stack Overflow

programmeradmin1浏览0评论

How can I count how many different values I have in 1 localstorage key.

For example:

This is my localstorage:

[{"id":"item-1","icon":"google"},{"id":"item-2","icon":"youtube"}]

For this example I'd like an alert of 2 different values. So basically I want to count the {}..

Is that possible?

How can I count how many different values I have in 1 localstorage key.

For example:

This is my localstorage:

[{"id":"item-1","icon":"google.com"},{"id":"item-2","icon":"youtube.com"}]

For this example I'd like an alert of 2 different values. So basically I want to count the {}..

Is that possible?

Share Improve this question asked Nov 11, 2011 at 11:54 jQuerybeastjQuerybeast 14.5k39 gold badges119 silver badges198 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

localStorage is an object, so just localStorage.length gives you the number of entries.

However I think I might be misunderstanding you. Do you mean you have one key, and that key's value is a JSON.stringify'd object? If so, you could do JSON.parse(localStorage.keyname).length to unserialise the value and count how many there are in there.

Your object is saved as an array so just using the .length should give you the number of {} pairs you have. Try this (replace "whatever" with the name of your array:

var something = localstorage.whatever[];
var length = something.length;
alert("length = " + length);

This will return the number of items in the key for you

testing = JSON.parse(localStorage.getItem(KEYNAMEHERE));

//Lets count how many we have back
obj = eval('(' + testing + ')');

//And the total is...
objCount=0;
for(_obj in obj) objCount++;

alert(objCount)
发布评论

评论列表(0)

  1. 暂无评论