Javascript pushing into array issue with parsing data from an object - javascript

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!

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 <

Related

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0') -- when all objects are not-undefined

Working on data visualization with d3.js. I'm quite a novice in javascript, but I come here trying to get to the root of my issue.
I'm trying to plot some movie-based data, in which every data point is the string data type. Therefore, I have to convert dates to the Date data type, and Movie Ratings to Number or Float data type for d3 to plot the data properly, else there's an error.
Pretty much, the data is stored in an array, which holds 11 other arrays, one for each movie critic, in which each movie critic array holds 237 objects for each movie watched that year, in which each object looks like
{
"key": "Derek",
"Date": "2019-01-25T05:00:00.000Z",
"value": 5,
"Movie": "The Butterfly Effect",
"Pickedby": "Dan"
}
Where key is the movie critic, and Pickedby is the person who picked the movie.
Here is the code I'm using to convert a date like 1/25/2019 into "2019-01-25T05:00:00.000Z"
and am trying to convert the value item (from a string) into a Number, or Floating Point Number. (Some ratings can be like 3.5, 6.5, etc.)
for (let j = 0; j < series.length; j++) {
for (let i = 0; i <series[j].length; i++){
series[j][i].Date = new Date(series[j][i].Date)
series[j][i].value = Number(series[i][j].value)
}
}
The date conversion line of code works as expected.
However, converting the value item into a Number or Float is causing Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0') error to arise.
The thing is, all of the value items data through the entire array is a string. There isn't an undefined issue. Sure, some values are (x's) or some other alphabetical character, but that should be converted to NaN at least, and it is for some.
Any thoughts on why this error could be arising, given the information I have provided? I can always probably provide more detail.
Thanks!
It looks like a typo was made in the code, where you are not accessing the correct value in the cast to Number.
Instead of:
series[j][i].value = Number(series[i][j].value)
it should be:
series[j][i].value = Number(series[j][i].value)

SuiteScript / JavaScript Array Indexing Issues

I am working on dynamically generating XML for printing labels. I have an array of values generated with map, the format of this array should end up as such:
[[val1a, val1b, val1c],[val2a,val2b,val2c],[val3a,val3b,val3c]]
I am unable to log to the browser console in this application, so must use provided logging APIs to view the actual values of the array at any given point. The format presented by logging is as such:
val1a,val1b,val1c,val2a...
The values are generated like so:
for(var i = 0; i < lines; i++) {
for(var j = 0; j < quantity; j++){
smCnts.push([i]);
}
}
Where i is the line number of the specific "record", and j is iterating over the quantity, pushing the line number to the array smCnts. Resulting in a dataset like this (assuming line 1 has a quantity of 3, and line 2 has a quantity of 2 etc.):
[[1], [1], [1], [2], [2], [3]]
This array is then mapped using a function that gets values from the lines:
var smLbls = smCnts.map(getData);
Resulting in something like the first array listed in this question.
The problem results when trying to index the array for a specific value:
var foo = smLbls[1];
This returns nothing, I don't even know if it returns null as the logging api returns only: .
However, logging smLbls returns the first mentioned array as described in the second code snippet. What would be causing this issue? I need to be able to get the index of the index of an array like so:
var bar = smLbls[1][3];
Everything else is working as expected, I am just unable to access this data for whatever reason, maybe I am not understanding JavaScript fully?
I am unable to log to the browser console in this application, so must use provided logging APIs to view the actual values of the array at any given point. The format presented by logging is as such:
My advice, use the logs to extract a snapshot of your data:
nlapiLogExecution('debug', 'sample', JSON.stringify(data));
...and work in the browser.

JSON.parse(json_string_from_php) produces weird array

I'm having a bit of difficulty with transferring a JSON object from the server to the client-side javascript
I have a rows of data fetched from MySQL query stored into $result
Here's the code:
var json = '<?= json_encode($result->fetch_all()) ?>';
var word_list = JSON.parse(json);
console.log(word_list); //index.php:23
console.log(json); //index.php:24
This is the result in chrome console:
Can someone tell me:
1. Why line 23 shows length of 5 when folded, then only show length of 4 when unfolded?
2. Where did word5 go? FYI, the word that disappears changes every time I refresh.
I am able to reproduce your screenshot.
I purposely hovered over the little "i" to reveal its tooltip. It states "Object state below is captured upon first expansion.
This means that if you print the array, don't expand it, modify the array (say with a pop()) then when you expand it you will see the modified array.
Demo: JSBin
console.log logs your state of the object to the console when it is hitting the console.log while inspecting the array (or any object) shows you the current state of it.
var a = [1,2,3,4,5].map(function(){ return new String(); });
console.log(a);
a.pop();

Parsing a JSON object of arrays gives different results in IE9

Intro
I am working on creating a HighCharts graph from a DataTable table.
What I do is iterate over the the rows and columns of the table, convert the strings (we use different thousand separators from the US) to numbers and save them into an object called item. the object has two values item["name"] which is the name of the series and item["data"] which is the data for the series. I then use the .push method to add these objects to an array to send to a Highcharts options object to create the plot. In the case below, I only have three series, but the problem always occurs. The LineOptions is an options-object for the HighCharts Graph.
Code
function plotLineOrBar(type){
var jsonData = [];
var xaxis = $('#masters_table table').find('thead th:not(:first-child)').map(function(){
return $(this).html();
}).get();
$('#masters_table table tbody tr').each(function(){
item = {};
item["name"] = $(this).find('td:first-child').html();
item["data"] = $(this).find('td:not(:first-child)').map(function(){
return parseInt($(this).html().replace(/\./g, "").replace('',0),10);
}).get();
jsonData.push(item);
});
console.log(jsonData[0]["name"]); // send the 0th name to console
console.log(jsonData[1]["name"]); // send the 1st name to console
console.log(jsonData[2]["name"]); // send the 2nd name to console
LineOptions.series = (jsonData);
LineOptions.xAxis.categories = xaxis;
LineOptions.chart.type=type;
var chart = new Highcharts.Chart(LineOptions);
}
Problem
(The name of the series should be 2320,2321,2336)
In Chrome, the resulting console.log is:
2320
2321
2336
and the corresponding data to each series prints out correctly and everything works flawlessly.
In IE9, the resulting console.log is:
LOG: 2336
LOG: 2336
LOG: 2336
i.e., only the last series gets printed into the array. The result is three series with perfectly overlapping curves, since they have the same data.
I have searched and searched for answers, wrapped by brain around but I can still not figure out what I am doing wrong. I assume though, that my error is a simple one (I hope).
As previously wrote in the comment (for future reference), just define the item variable inside of the loop function, instead of using a "global" one (var item = {} instead of item = {}). This is because in IE9 it seems to be passed by reference, and thus you're pushing the very same object, updated three times (changing its values from iteration to iteration).
P.S.
by the way it seems that the other browser you're using, it is creating a new variable every time you use .push and I'm not sure that's the "standard" behavior. One point to IE9!

Changing the variables of a class in OOP in javascript

I have defined a function called Node which stores the properties of nodes in a graph data structure. The function is something like this:
function Node(){
...
this.outEdges = [];
this.inEdges = [];
...
}
where the inEdges and outEdges store elements of type Edge which is another function I have defined. During the program these arrays are filled with elements.
At some point in my code I need to reset these two arrays so I write:
nodes[i].outEdges.length = 0;
nodes[i].inEdges.length = 0;
where nodes is an array of elements of type Node and I am accessing an element in a for loop.
The problem is, after setting outEdges and inEdges to 0, I expected them to be [] in the nodes[i] property list. However, when I output nodes[i] into console, the outEdges and inEdges still have the elements in them. The stranger thing is that when I output nodes[i].outEdges to console, it prints [] , which is correct, but clicking on [ ] again opens the list of the elements! I can't really figure out why the nodes[i] variables don't change?
That happens (probably) because the browser prints out the empty array but by the time you check it, it has content again. So when you click to expand the browser shows the actual content.
As you can see the values [1,3,7] were added after the command console.log(o) but they are shown on the screen (even though the length shown is 0).
You're not supposed to set the length field. Just re-initialize them:
nodes[i].outEdges = [];
nodes[i].inEdges = [];
Edit: My bad, setting the length should work. It does work for me on Chrome at least. However, I still think it's safer and better style to re-init.
Just create a new object with the same name
nodes[i].outEdges = new Array();

Categories