Get only one element from an array of objects in JSON

How can I get only the name from the JSON file. Also, the code works great for getting data from file.json, i.e. It's not a problem.

JavaScript:

var data = []; function getName() { //what should I write here to get only name from the first object ie John //with this: data[0].name I am getting error! } var xhttp; if(window.XMLHttpRequest) xhttp = new XMLHttpRequest(); else xhttp = new ActiveXObject("Microsoft.XMLHTTP"); xhttp.onreadystatechange = function() { if(xhttp.readyState == 4) { data = JSON.parse(xhttp.responseText); getName(); } } xhttp.open("GET","file.json",true); xhttp.send(); 

"file.json" - JSON:

 [ { "name":"John", "city":"London" }, { "name":"Maria", "city":"Rome" } ] 
+5
source share
4 answers

Pass variable data through function

 var data = []; function getName(data) { return data[0].name; } var xhttp; if(window.XMLHttpRequest) xhttp = new XMLHttpRequest(); else xhttp = new ActiveXObject("Microsoft.XMLHTTP"); xhttp.onreadystatechange = function() { if(xhttp.readyState == 4) { data = JSON.parse(xhttp.responseText); getName(data); } } xhttp.open("GET","file.json",true); xhttp.send(); 

Also, if you want to get all the names, you can do something like this:

 function getName(data) { var names = []; for (var i = 0; i < data.length; i++) { names.push(data[i].name); } return names; } 

(Data is array data)

+6
source

Use Array.prototype.map () to transfer the elements of your array:

 data.map(function(item) { return item.name }); 
+4
source

Your getName function should look like this:

 function getName(){ a.forEach(function(i,j){ console.log(i.name); }); } 
+1
source

It is worth noting that JSON data types are directly mapped to standard javascript data types. This means that there is no such thing as a JSON array after the JSON.parse() , then you will get simple javascript primitives: arrays, objects, strings, numbers, etc.

Thus, getting an element from a JSON array is simply accessing an element of a standard javascript array. This is usually achieved using the square bracket operator var element = array[index] .

However, your code is broken into several parts that are not related to accessing an array element.

First, you define the data variable at the top level - you just don't need it there (at least according to the sample).

Then you initialize it with an empty array - I have no idea why.

The onreadystatechange is simple when expressed in words: you get a string, parse it as json, and then call getName , providing the result. This means that your getName() should need the data argument, which you then get as part of the function.

0
source

Source: https://habr.com/ru/post/1239276/


All Articles