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);
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
My JSON-File:
[
{
"state": "geschlossen",
"number": 1,
"class": "A",
"price": 10
},
{
"state": "geschlossen",
"number": 2,
"class": "B",
"price": 20
},
{
"state": "geschlossen",
"number": 3,
"class": "C",
"price": 30
}
]
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
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?
CodePudding user response:
It looks like you have to use the obj.price
instead of the obj.name
here:
var index = jsonArr.findIndex(obj => obj.name===price);