简体   繁体   中英

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?

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.

Assuming you are talking about a very traditional web page, where you have in your HTML something like:

<script src="garage.js"></script>
<script>
    myObject.cars[0].body.width = 6;
    console.log(myObject.cars[0].body.width);
</script>

Then your comment demonstrates a misunderstanding of terms:

It all has to be done locally, and with no database...

Even if this is all running locally on your computer, unplugged from any network, there is still a client and a server , they just both happen to be the same computer. That's the nature of a web app, it's always client/server.

So, you want to save it on the server (which may be the local machine - doesn't matter). In that case you have to be running server code. Something like PHP, ASP.Net, Java/Tomcat, Ruby, Node.js, etc. It is the server code that does the saving.

First thing I would recommend is to store your values as JSON, not JavaScript. It is easier to write a JSON file, but writing JavaScript would be prone to bugs.

All you need to change in your file is to remove var myObject = and also the trailing semi-colon, then save as garage.json . Then, in your script, you would retrieve the JSON with an AJAX call and parse it. Once changed and ready to save, you would .stringify() your JavaScript object and send it back to the server via AJAX to be saved.

There are many libraries that will make the AJAX calls easy for you, but if you want a VanillaJS example, here is one way you could make the AJAX calls to read and write the JSON:

function getJSON(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onreadystatechange = function(e) {
        if (this.readyState == 4 && this.status == 200) {
            callback(JSON.parse(this.responseText));
        }
    };
    xhr.send();
}
function saveJSON(obj, url) {
    var json = JSON.stringify(obj);
    var payload = "path=" + encodeURIComponent(url);
    payload += "&json=" + encodeURIComponent(json)
    var xhr = new XMLHttpRequest();
    xhr.open("post", "jsonSaver"); // path to server code
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.send(payload);
}
getJSON("garage.json", function(myObject) {
    myObject.cars[0].body.width = 6;
    saveJSON(myObject, "garage.json");
});

You would have to create a server-side handler to actually write the JSON file. And how you do that depends on the server-side language you want to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM