When an object is not empty, the function Object.getOwnPropertyNames will still return an empty array

In my code, I am filling $scope.master with data from a csv file. When I populate $scope.master within the function, all the data is present. This can be observed in the log output displayed below.

However, outside of the function, although $scope.master contains the expected data, when I execute

console.log(Object.getOwnPropertyNames($scope.master))
, it returns an empty array, and
console.log(Object.getOwnPropertyNames($scope.master).length)
also returns 0.

Why does the seemingly non-empty $scope.master object show an empty array for its properties?

angular.module('app', []);
angular.module('app').controller('mainCntrl', ['$scope', 
function ($scope) {

  $scope.master = {}; 
  $scope.selected_interface = "";
  $scope.selected_DBCfile = "";
  $scope.DBCfiles = [];

  var CSV_filepath = '../data/interfaces.csv';

  d3.csv(CSV_filepath, function (err, data) {
    data.forEach(function (d) {
      d.interfaceName = d.interfaceName;
      d.DBCfile  = d.DBCfile;
      d.AtoB = +d.AtoB;
      d.BtoA = +d.BtoA;

      if (!$scope.master[d.interfaceName]) {
        var DBCfilesForInterface = {};
        DBCfilesForInterface[d.DBCfile] = new Array();
        DBCfilesForInterface[d.DBCfile].push(d);
        $scope.master[d.interfaceName] = DBCfilesForInterface;
      }
      else if (!$scope.master[d.interfaceName][d.DBCfile]) {
        $scope.master[d.interfaceName][d.DBCfile] = new Array();
        $scope.master[d.interfaceName][d.DBCfile].push(d);
      }
      else{
        $scope.master[d.interfaceName][d.DBCfile].push(d);
      }
    })

    //master is all made
    $scope.interfaces = Object.keys($scope.master);
    $scope.selected_interface = $scope.interfaces[0];
    $scope.DBCfiles = Object.keys($scope.master[$scope.selected_interface]);
    $scope.selected_DBCfile = $scope.DBCfiles[0];


//LOOK AT THESE LOGS
    console.log($scope.master);
    //Object { 1 - ModelS ESP 1.0 Interface: Object, 2 - ModelS ESP 2.0 Interface: Object, 3 - ModelS ESP 2.0 Interface with Tesla Body Controls: Object, 4 - ModelS ESP 2.0 Interface with Tesla Body Controls and TH bus: Object }

    console.log($scope.selected_interface);
    //"1ModelSESP10Interface"

    console.log($scope.selected_DBCfile);
    //"ModelSBDYdbc"

    console.log($scope.DBCfiles);
    //Array [ "ModelSBDYdbc", "ModelSBFTdbc", "ModelSCHdbc", "ModelSETHdbc", "ModelSOBDIIdbc", "ModelSPTdbc", "ModelXTHcommondbc" ]

  });

//OUTSIDE OF THE FUNCTION
    console.log($scope.master);
    

    console.log(Object.getOwnPropertyNames($scope.master));
    

    console.log(Object.getOwnPropertyNames($scope.master).length);
    

    console.log($scope.selected_interface);
    

    console.log($scope.selected_DBCfile);
    

    console.log($scope.DBCfiles);
    
}]);

Answer №1

The reason for this behavior is due to the asynchronous nature of the d3.csv method.

Any code outside the function will execute before the data is fully processed and stored in variables. To ensure that all values are populated correctly, it's important to place any data processing methods within the callback of the d3.csv method.

I trust that this explanation proves helpful to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty in replicating and obtaining flash video content from a website through HTML coding

I'm having trouble downloading a flash video, as traditional download software isn't working. I attempted to directly access the video from the html script itself, following this tutorial : https://www.youtube.com/watch?v=waE3J0Jej_0 The script ...

Changing a variable within a method does not automatically reflect in the child component

Need help with Vue update process for props/child components. Consider this component: <template> <v-card> <Modification v-model="newObject"></Modification> <OtherComponent @close="resetObject">& ...

Is it possible to decrease the size of a div by scrolling both vertically and horizontally?

Can a div's height and width both be reduced at the same time while scrolling down a page? Let's say that as the user scrolls, the size of the div changes from 400px by 400px to 200px by 200px, all while remaining centered on the page. I've ...

The access-control-allow-headers token is absent from the CORS header 'Access-Control-Allow-Headers' during the CORS preflight process

I am facing an issue with two VS projects: one has MVC5 controllers exposed, while the other is an Angular client. I need the Angular client to be able to query the controllers. I have done some research and attempted the following steps: I added the f ...

Retrieve a div element using Ajax from the result of an If statement

I need to extract a specific div from the data returned by an if statement that is formatted as HTML, and then display it within another div. I have been attempting to achieve this using the code below, but so far it has not been successful... Here is my ...

Is it better to utilize a sizable JavaScript file or opt for a compact one?

I recently created a JavaScript file with over 6000 lines of code for various sections of my website. I'm debating whether to keep it as one large file or break it up into smaller parts and call them in their respective sections. What do you think? ...

What is the best way to access a Python API or local data within the Google Visualization DataTable JavaScript library?

I have been tirelessly working for the past two weeks to figure out how to load a local CSV file into google.visualization.DataTable() or use Ajax to call a Python Flask API that I created. My ultimate goal is to dynamically create a Gantt chart. Here&apo ...

Find the total of values in an array that may be null or undefined

In this scenario, I have an array that looks like this: myData = [[2, null, null, 12, 2], [0, 0, 10, 1, null], undefined]; The goal is to calculate the sum of each sub-array, resulting in an array like this: result = [16, 11, 0]. The ...

Do we need to specify ngRoute in the angular module configuration?

Being new to angular.js, I have a question about ngRoute - is it necessary to define it on the angular module? From what I understand, it is required if we want to update the view based on URL changes. But can we also manually define routes and return vi ...

Data within object not recognized by TableCell Material UI element

I am currently facing an issue where the content of an object is not being displayed within the Material UI component TableCell. Interestingly, I have used the same approach with the Title component and it shows the content without any problems. function ...

Querying data from a promise and embedding it in a JSON object in AngularJS

Attempting to retrieve data from a promise within a JSON object for the first time has presented me with a challenging task. The typical approach looks something like this: Service JS app.factory("dataService", ["$http", function ($http) { fu ...

The declaration file for the 'react' module could not be located

I was exploring Microsoft's guide on TypeScript combined with React and Redux. After executing the command: npm install -S redux react-redux @types/react-redux I encountered an error when running npm run start: Type error: Could not find a decla ...

Alternative form for non-javascript browsers in the absence of script

I'm currently working on a landing page for an upcoming product, and I've run into a bit of a snag. <form novalidate method="POST" class="subscribe-form"> <noscript> </form> <form method="POST" action="/ ...

Refreshing data and manipulating arrays using AngularJS

Currently, I am developing an application utilizing AngularJS and LocalStorage. I've encountered a challenge that seems a bit too intricate for me to handle. The app involves managing lists of people with the ability to add arrays of names. The proce ...

The functionality of AJAX is successful when tested on a local server, but encounters issues when deployed on a live

While the following code functions correctly on localhost, it fails to work on the live server. IMPORTANT UPDATE: There's only 1 issue remaining: Upon successful execution of this AJAX block: $(".FixedDiv").addClass("panel-danger"); setTimeout(c ...

Rendering data from an API using v-if

Could you help me change the tag that currently displays true or false? I want it to show "FREE" if the event is free and "PAID" if it's not. Check out the Eventbrite API here The response I'm receiving from data.events.is_free is in boolean fo ...

Is there a way to modify a document without altering its original location?

I attempted to load an entire page using ajax, with the doctype and html tags removed. However, when I tried setting it with the following code: document.documentElement.innerHTML=xmlhttp.responseText; Google Chrome returned an error message: An invalid ...

How can you determine if a polymer element has been loaded or not?

element, I am interested in dynamically importing elements using the Polymer.import( elements, callback ) method. The callback is triggered only if the elements have not been imported yet, indicating they are already loaded. My query is: Is there a conve ...

Button fails to display as intended despite meeting conditions

I'm currently using a formData object with useState(). Whenever a field is updated in the form, I update formData like this: setFormData({...formData, [field.id]: field.value}) My goal is to have the button at the end of the form change once all req ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...