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

Is $httpBackend failing to mock the request and response?

Attempting to test the $scope.init(id) function involves making a request to the API that returns an array of objects, which needs to be stubbed out with a preset response. Test failure: describe('mysite', function() { var scope, MensDetailCt ...

Building New Web Pages with Express in Node.JS

I want to dynamically generate a new page on Node.JS with Express upon user form submission. Here is my initial approach, but it's not working as expected: var app = require('express')(); var server= require('http').createServer(a ...

Is it possible to verify whether a Node Js query is empty or not?

I've been attempting to determine if a result query is empty or not, conducting thorough research in the process. Below is the code illustrating the query I'm executing and the two methods I employed to check if it's empty. The issue at han ...

The utilization of the jquery.form.js plugin is resulting in my form being submitted twice

In order to enable Ajax file uploads in my ASP.Net MVC project, I am utilizing the jquery plugin known as "jquery.form.js" (http://malsup.com/jquery/form/#getting-started). However, I am encountering an issue where the controller action responsible for han ...

Constructor-generated element doesn't reflect changes upon component re-rendering

Why doesn't the <select> I create in the constructor update correctly when I select a different flavor? The other select and text update, but not this one. class ConstructorComponent extends React.Component { constructor() { super(); ...

Issue with $scope.gridOptions.api.setRowData function not being effective

I am currently working with ag-grid and facing an issue where I am unable to display data from a JSON file on the UI using the $scope.gridOptions.api.setRowData method. Currently, only the headers are being displayed but not the data itself. Below is the ...

Implement a click event for the X-Axis label in Angular 2 Highcharts

I'm currently facing a challenge with hand-rolling a solution that involves adding a click listener to an X-Axis label in a column chart using the HighCharts API within an Angular 2+ application. Here is what I have gathered so far: I am utilizing ...

When using ng-repeat in Angular.js, an additional td is created

https://jsfiddle.net/gdrkftwm/ https://i.sstatic.net/CTi2F.jpg I have encountered a problem while creating a table from a Json object. There seems to be an extra td being generated, and I'm not sure why. I want the structure of my table to resemble ...

Oops! Make sure to call google.charts.load before calling google.charts.setOnLoadCallback to avoid this error

My HTML file includes the following imports: <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> ...

Incorporating fresh components and newly defined attributes in Angular

Is there a way for me to click on a new component button, specify a name, description, select type, and add attributes such as default value and type? I need all this information to be saved and for the new button to appear in the drag-and-drop section. ...

Encounter a Config validation error while trying to utilize Nest.js ConfigService within e2e tests

I'm encountering an error despite having the NODE_ENV=development variable in my .env file. The error message reads: ● Test suite failed to run Config validation error: "NODE_ENV" must be one of [development, production] 11 | imports ...

Unpacking JSON Objects in Typescript: Working with Private Variables

I have a TypeScript model object called user export class User { constructor( private _name: string, private _email: string ) {} public get name():string { return this._name; } public set name(value:string) { this._name = value; } g ...

Axios removes the async functionality

Is there a way to achieve the same functionality without using the async function? async EnvioLogin() { const response = await axios.post("api/auth/login", { email: this.email, password: this.password, }); localStorage.setItem(" ...

Attempting to change the background color of a table row when hovering in React, but experiencing no success

Describing the appearance of my table row: <tr onMouseEnter={() => {this.buttonIsHovered = true} } onMouseLeave={() => {this.buttonIsHovered = false}} className={this.buttonIsHovered ? 'hover' : null}> The initial value ...

Pressing a button triggers an Ajax response, but in CasperJS it results in the entire page being refreshed

Recently, I've been experimenting with CasperJS in an attempt to identify Free-Email Alias on My focus is on the input field labeled "E-Mail-Wunschname:" where I intend to input a name, click the "Prüfen" button, and then extract the suggested accou ...

Looking for a specific search term within the middle of strings in an array

Is there a way to improve the autocomplete feature of my input field so that it shows suggestions based on any part of the word typed in? I currently have it set up to only show suggestions if the input matches the start of a word in the array. How can I m ...

Update the color of navigation items to reflect their active status

Here is the snippet of HTML code: <header> <nav> <a href="#" id="menu-icon"></a> <ul> <li><a href="#"">Home</a></li> <li><a href="#">About</a></li> & ...

Update the positioning of the element to center instead of the default top left origin using jQuery

I am facing an issue with positioning a marker inside a triangle, which is represented by a simple div, as shown in the image below: https://i.stack.imgur.com/0Q7Lm.png The marker needs to be placed exactly at the centroid of the triangle. However, it see ...

Issue: Module '../utils/composeObjs' not found after global installation of generator-stencil

Currently, I am in the process of developing a generator for stenciljs which can be found at https://github.com/AkashGutha/generator-stencil Within this project, there is a handy utility function located at the root directory. This function resides in one ...

Creating various containers in React JS for different components

I am faced with the task of rendering multiple DOM elements from my JavaScript code. Imagine I have div elements like this: <div id="div1"><div> //Some Html tags <div id="div2"><div> //Some Html tags <div id="div3" ...