check if a value of a variable exists in localStorage check if a value of a variable exists in localStorage json json

check if a value of a variable exists in localStorage


Try:

if(tweeting !=JSON.parse(localStorage['tweet_text']))

Or:

if(JSON.stringify(tweeting) != localStorage['tweet_text'])

You are comparing an object with JSON, it will never be the same.


As the data is in a 'for' loop the SINGLE local storage item's value is being overwritten by each tweed ID until the loop ends. This means that the final value of the localStorage item will always be the last tweet ID in the for loop. Because of this both values will never match, causing it to always get inside the 'if' statement.

Thanks to @hodaya's answer, the value of the JSON object must also be converted to a string before it is compared to the localStorage item. This is because localStorage only stores values as strings. From the examples given in @hodaya's answer; 'JSON.stringify' is used to convert an array to a JSON string, and 'JSON.parse' is used to convert a JSON string back to an array. SOURCE: Microsoft. So neither of these answers solved the problem on their own.

ANSWER:

The value of the JSON object must be converted to a string. A counter must be included to make a new localStorage item unique to each iteration in the 'for' loop.

r=0;for(i=0;i<tweets.length;i++){    //must have a counter added to each localStorage item to make it unique.                                       r+=1;    //transforming the JSON id_str into a JavaScript object.    tweetID = jQuery.parseJSON(tweets[i][0].id_str);    //tweetID is now an integer value    //converting it to a string ready for localStorage.    tweetIdString = tweetID.toString();    if(tweetIdString != localStorage['tweet_id' + r]){       alert("new tweet");      localStorage['tweet_id' + r] = tweetIdString;        console.log(localStorage['tweet_id' + r]);   }}

Hey, presto!