Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store changed values into a JavaScript object?

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?

like image 279
Kameron White Avatar asked Jun 22 '26 13:06

Kameron White


2 Answers

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.

like image 80
Antonio Smoljan Avatar answered Jun 24 '26 03:06

Antonio Smoljan


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.

like image 37
Lyes BEN Avatar answered Jun 24 '26 02:06

Lyes BEN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!