How to modify a Json object (javascript)?

2

I need to change a json Object that I'm receiving. I would like to insert a data of an input in this Json. The idea is simple put a data, it pulls the json according to this data, but I need to change the json with that same data. I need to change johnner in apiGet! Follow Code:

<!DOCTYPE html>
<html>
<body>
<h1>Meu Projeto</h1>
<div id="id01"></div>
Nome: <input type="text" id="nome" value="johnner">

<p>Click the button to change the value of the text field.</p>

<button onclick="teste()">Try it</button>
<p id="saida">aqui</p>

<script>

function teste() {
    	var x = document.getElementById("nome").value;
	var xmlhttp = new XMLHttpRequest();
	var url = "https://na.api.pvp.net/api/lol/br/v1.4/summoner/by-name/" + 
	x + "?api_key=a15c56d1-fdd7-4da2-ad9c-0f1a6585ac1b";

	xmlhttp.onreadystatechange=function() {
 	   if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        apiGet(xmlhttp.responseText);
	    	}
	}
	xmlhttp.open("GET", url, true);
	xmlhttp.send();
}

function apiGet(response) {
    var XX = JSON.parse(response);
    var arr = XX.johnner;
    var out = "<h1>";
    out += arr.id + arr.name + arr.summonerLevel;
    out += "</h1>";
    document.getElementById("id01").innerHTML = out;
}

function getImput() {
    var x = document.getElementById("nome").value;
document.getElementById("saida").innerHTML = x;
}

</script>
</body>
</html>

I need to change / access Json in this part: var arr = XX.johnner; using the same name that was passed in the ajax url.

AJAX returns this:

{"johnner":{"id":1111,"name":"Johnner","profileIconId":111,"summonerLevel":11,"revisionDate":1111111111}}
    
asked by anonymous 03.12.2015 / 21:33

1 answer

1

What you need is to use the x variable within the apiGet function to be able to access the property of the object dynamically, ie with [] straight parentheses.

I suggest changing the code as in the example below, which summarizing has these two changes:

  • calls apiGet passing x as parameter
  • uses var arr = XX[x]; thus accessing the property with the string you passed

JavaScript

function teste() {
  var x = document.getElementById("nome").value;
  var xmlhttp = new XMLHttpRequest();
  var url = "https://na.api.pvp.net/api/lol/br/v1.4/summoner/by-name/" +
    x + "?api_key=a15c56d1-fdd7-4da2-ad9c-0f1a6585ac1b";

  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      apiGet(xmlhttp.responseText, x);
    }
  }
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}

function apiGet(response, nome) {
  var XX = JSON.parse(response);
  var obj = XX[nome];
  var out = "<h1>";
  out += obj.id + obj.name + obj.summonerLevel;
  out += "</h1>";
  document.getElementById("id01").innerHTML = out;
}

Note: I also changed the code var arr to var obj because JSON gives you an object, not an array. This is more correct for those reading the code (semantically).

    
04.12.2015 / 10:44