Reputation: 137
I have this if statement where if the variable value is not equal to the localStorage value then execute the code.
for(i=0;i<tweets.length;i++){
tweetID = tweets[i][0].id_str;
if(tweetID != localStorage['tweet_id']){
alert("new tweet");
localStorage['tweet_id'] = tweetID;
console.log(localStorage['tweet_id']);
}
}
My problem is that it is always getting inside the if statement indicating that the value is never equal to the localStorage value. The first time this code runs it will always go into the if statement because the 'tweet_id' localStorage item is undefined. Once it gets inside it should then write the 'tweetID' value to the localStorage value, as you can see in my code. The page refreshes every 30 seconds and if there hasn't been a new tweet these values should match and not get inside the if statement.
This is not the case. What am I doing wrong?
From using console.log these values match after the first time it gets in the if statement, so it should not get in there again unless the value of tweetID changes. Any ideas would be greatly appreciated!
Upvotes: 3
Views: 1601
Reputation: 137
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!
Upvotes: 0
Reputation: 4417
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.
Upvotes: 1