Why is the array undefined
My question is how do i get to display the objects inside the results array. I've tried console.log(data.results[0].bodyColor) and i get an error. When i try (data.results) i get undefined. when i try (data.results[0]) it gives responds with a error message. Why is the array undefined when i can see it on my console. [this is the console so how can i print out the value of the AirBagLocFront][1]
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<h2> Vehicle API</h2>
<div id="div"></div>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<!--Jquery CDN-->
<script>
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
type: "POST",
cache: true,
data: {
format: "json",
data: "WBAPK5C52AA599960;"
},
dataType: "json",
success: function(data) {
console.log(data.results[0].AirBagLocFront);
}
});
</script>
</body>
</html>
You have a typo in your code. You want Results
, not results
. Moreover, Results
is an array containing a single object. You could traverse the entire data structure quite easily using a for...in
loop. Here is a working snippet:
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
type: "POST",
cache: true,
data: {
format: "json",
data: "WBAPK5C52AA599960;"
},
dataType: "json",
success: function(data) {
var res = data.Results[0];
for (var prop in res) {
if (res.hasOwnProperty(prop)) {
console.log(prop + ' - ' + (res[prop] ? res[prop] : 'N/A'));
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>