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"
}
]
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, '['.
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() .
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.
Sure, you can use JS's foreach.
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)
Use Array.prototype.map() to transfrom items of your array:
data.map(function(item) {
return item.name
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With