Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

XMLHttpRequest manipulate JSON-File

trying to do a XMLHttprequest to manipulate a JSON and save it on my local drive.

Here is the code:

   
     function xml(){
        var xhr = new XMLHttpRequest(),
            jsonArr,
            method = "GET",
            jsonRequestURL = "win_lose.json";
        price = $('#price').val();
        xhr.open(method, jsonRequestURL, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // we convert your JSON into JavaScript object
                jsonArr = JSON.parse(xhr.responseText);
                var index = jsonArr.findIndex(obj => obj.name===price);
                jsonArr.splice(index);
                console.log(price);
                console.log(index);
                xhr.open("POST", jsonRequestURL, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.send("jsonTxt=" + JSON.stringify(jsonArr));
            }

        };
        xhr.send(null);
    }

My JSON-File:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
   {
      "state": "geschlossen",
      "number": 1,
      "class": "A",
      "price": 10
    },
    {
      "state": "geschlossen",
      "number": 2,
      "class": "B",
      "price": 20
    },
    {
      "state": "geschlossen",
      "number": 3,
      "class": "C",
      "price": 30
    }
  ]

findIndex gives me the everytime the index -1 doesnt matter if i enter the value 10,20 or 30 but i expect :
price : 10 -> index 0 ; price : 20 -> index 1 ; price : 30 -> index 2 ;

So where is the problem with the findIndex?

>Solution :

It looks like you have to use the obj.price instead of the obj.name here:
var index = jsonArr.findIndex(obj => obj.name===price);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading