I have this JS object that is stored in a file called garage.js:
var myObject = {
"cars": [
{
"type": "mustang",
"body": {
"length": 10.7,
"width": 5.8,
"color" : "#fff"
}
},
{
"type": "corvette",
"body": {
"length": 11.9,
"width": 5.6,
"color": "#000"
}
}]
};
When I make changes to the width wtihin a JS function within html, like this:
myObject.cars[0].body.width = 6
and then check the variable to see if the value has been updated, like this:
console.log(myObject.cars[0].body.width = 6)
the console prints 6... but it does not change the value in the stored object in garage.js... (how do I do this?)
The value appears to be represented locally but I need it to actually write this updated value back to the garage.js file so that it is stored permanently, so that when I refresh the html in the browser, the new value, 6, will have replaced the old value, 5.8, in the myObject object.
Do I need to use JSON.stringify and JSON.parse? ... or is it much simpler than that?
You could use localStorage to save the state easily. It would look something like this :
localStorage.setItem("width", "6") setting the key,value pair
myObject.cars[0].body.width = localStorage["width"] making the value of with equal the localStorage value.
Now each time you open the web page the value should be 6.
Or alternatively you can use databases to store and retrieve the value.
Your JSON files are stored on the server, not on the browser (localStorage) I guess.
Since you cannot write to files stored on the server with browser Javascript, you might need a backend solution. If you still want to code with Javascript, use node.js to load your .json files, edit them and apply changes directly to the files.
If you want more details, you can comment on this entry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With