Reputation:
I am making a completely offline HTML5 web app.
In a particular part of my code, I am required to add a row of data to a JavaScript Array Object and save the updated version back to localStorage
.
Here is the code:
var data = localStorage.getItem("cars");
//Trouble in this line.
data.goals.push(["name": "merscede", "model": "bmw", "noofdays": "10", "active": "yes"]);
localStorage.setItem("goals",data);
And this is the value I had stored in the localStorage in a different part of the source code:
var data = '{"goals":[{"name":"rocky","model":"old","noofdays":"50","active":"no"}]}';
localStorage.setItem("goals",data);
I have troubleshooted extensively and it turns out that only the line that I have particularly marked has all the trouble.
What's the problem? What should I do?
Upvotes: 0
Views: 85
Reputation: 1638
This is how you need to do it :
var data = '{"goals":[{"name":"rocky","model":"old","noofdays":"50","active":"no"}]}';
localStorage.setItem("goals",data);
// You get a string when you do "getItem"
var goalsStr = localStorage.getItem("goals");
// You need to parse it.
var goalsObj = JSON.parse(goalsStr);
goalsObj.goals.push({"name": "merscede", "model": "bmw", "noofdays": "10", "active": "yes"});
console.log(goalsObj);
Upvotes: 1