Unable to compare a JavaScript variable with JSON data

913 views Asked by At

I have a table stored as a string in a JSON data in localstorage. I want to compare one of fields stored here to a separate javascript variable.

Here is what I have tried:

var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr); 
for (i=0; i<goalsObj.goals.length; i++) {
  if (goal==goalsObj.goals[i].goal) {
    //.....
    //.....
  }
}

But it is not working. After some trouble shooting, I think that the problem is in comparing (goal == goalsObj.goals[i].goal).

And this is the value that was actually stored inside "goals" in localStorage:

var data = '{"goals": [{"goal":"'+goal+'","duedate":"'+date2+'","noofdays":"'+diff+'","active":"'+active+'"}]}';
localStorage.setItem("goals",data);

It is an array of objects stored within.

All these 'diff', 'duedate' are HTML form data taken from users.

What's wrong? What should I do?

1

There are 1 answers

5
Adam Rackis On

Data appears to already be valid JSON. Why are you stringifying it? I think you want to do just

var data = '{"goals": [{"goal":"'+goal+'","duedate":"'+date2+'","noofdays":"'+diff+'","active":"'+active+'"}]}';
localStorage.setItem("goals", data);

and then when you pull that value back out, convert it to a JavaScript object via

var obj = JSON.parse(localStorage.getItem("goals"));