I am using $.getJSON
and $.each
to call a JSON end point and retrieve data. When I call the data, I put it in an object and then check it in the console. However, when I check the console, there is only one entry.
Why is only one entry being returned? What am I doing wrong?
JavaScript:
$(document).ready(function() {
var url =
'https://data.montgomerycountymd.gov/resource/housing-code-enforcement.json?street_number=9903';
var myJson = {};
$.getJSON(url, function(data) {
$.each(data, function(i, field) {
myJson = data;
});
console.log(myJson);
});
});
Hell seeing as everyone is repeating themselves thought id get in on the action.
As @RoyMcCrosan said your data value is an array, however your myJson
variable is an object. What you doing is looping through the array an placing each cell in that array into the myJson
variable, (here's the important bit), overwriting the value before it. So you end up with only the last value in the array.
Now without knowing what you want to do with the data we can't really say what you should do but here's a few common cases ive had to do:
If you want to simply copy the data and work with it else where as an array simply scrap the $.each
var myJson = [];
$.getJSON(url, function(data) {
myJson = data;
console.log(myJson);
});
If you want to map the data to end up with an array but in a different format:
var myJson = [];
$.getJSON(url, function(data) {
myJson = data.map(function (d) {
return {}; //Some modified object
});
console.log(myJson);
});
If you want to iterate the array and extract a property from each object to add to you myJson
variable;
var myJson = {};
$.getJSON(url, function(data) {
data.forEach(function (d) {
//Some logic for figuring property name.
var i = 'FieldName';
myJson[i] = d[i];
});
console.log(myJson);
});
Finally as data
is an array using native looping methods such as .forEach
or a for
loop. They will be faster then $.each
. Also technically myJson
is not JSON its a JavaScript object in its own right.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments