Mike Cuddy Mike Cuddy - 2 months ago 10
Javascript Question

Javascript pushing into array issue with parsing data from an object

I am currently working on a project what requires me to use the US Census Bureau API. I have most of my code working on my portion of the project however, I am having a small issue that I do not understand. What I am trying to do is take a 113 objects, parse one property from each of those objects, and then place that property, all 113, into an array. Like I said, I almost have my code working. Below is what does work:

for (var i = 0; i <= response.features.length; i++){
var dataPoint = response.features[i].properties.B19013_001E;
console.log(dataPoint);
}


The above code will print out all 113 points that I need to the console. (For those that are curious, the B19013_001E is median household income and that is the data that I want for basically a 113 different 'areas' within a county.)
Now, the code does what I want but now when I make the array portion:

var dataArray = [];

for (var i = 0; i <= response.features.length; i++){
var dataPoint = response.features[i].properties.B19013_001E;
dataArray.push(dataPoint);
}

console.log(dataArray);


When I console log my array, I only get this error message:
play.js:93 Uncaught TypeError: Cannot read property 'properties' of undefined

What I don't understand is how come I can get all 113 points that I need individually to the console but I have an issue when I am putting them into the array? One thing that I thought of was that maybe one of the points is not present? But when I look at the console logging of 113 points I get nothing as null or undefined. Any help will be great and thank you!

Answer

You should use Array.map:

var dataArray = response.features.map(function(feature) {
   return feature.properties.B19013_001E;
})

You are getting that error because <= puts the last iteration outside of the bounds of your data collection. You could just change that to <