Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only one element from array of objects in JSON

How can I get only the name from JSON file. Also code is perfectly working for getting the data from "file.json" i.e. that's not the problem for sure.

JavaScript:

var data = [];
function getName() {
  //what should I write here to get only name from the first object i.e. 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"
  }
]
like image 396
Nenad Jovanoski Avatar asked Dec 26 '15 23:12

Nenad Jovanoski


People also ask

How do you access the first element of a JSON object array?

To answer your titular question, you use [0] to access the first element, but as it stands mandrill_events contains a string not an array, so mandrill_events[0] will just get you the first character, '['.

How do you get a specific value from an array in JavaScript?

JavaScript Demo: Array.find() If you need to find the index of a value, use Array.prototype.indexOf() . (It's similar to findIndex() , but checks each element for equality with the value instead of using a testing function.) If you need to find if a value exists in an array, use Array.prototype.includes() .

Can you JSON parse an array?

Use the JSON. parse() method to pase a JSON array, e.g. JSON. parse(arr) . The method parses a JSON string and returns its JavaScript value or object equivalent.

Can I use foreach on JSON?

Sure, you can use JS's foreach.


2 Answers

Pass the variable data through the 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 retrieve all 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;
}

(The data is the array data)

like image 50
Ignacio Chiazzo Avatar answered Oct 10 '22 02:10

Ignacio Chiazzo


Use Array.prototype.map() to transfrom items of your array:

data.map(function(item) {
    return item.name
});
like image 31
madox2 Avatar answered Oct 10 '22 03:10

madox2