What is the best way to obtain an array format in JavaScript?

In AngularJs, I am retrieving an array using a factory function. This is the console output:

Array[0]
  0: "value1"
  1: "value2"
  length:2

However, when I try to get the length of the array:

console.log(array.length)

I am fetching data from MySQL in Loopback.

 app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    } 
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    return array;
        });

        return array;
      }
  }
});

The controller code looks like this:

app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
var emails = getFoo.getCommi(3,1);

setTimeout(function(){
    $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
}, 0)
}])

Even though it seems like there should be data in the array, the length is showing as 0. Why is that happening?

Answer №1

It seems that there is a timing discrepancy at play here. Initially, when you inquire about the length of the object, it appears to be 0. However, upon further inspection using Chrome Dev Tools a few moments later, you will find that the object has been populated in real-time.

You can verify this by employing the use of setTimeout

setTimeout(function(){
   console.log(array);
}, 0)

To delve deeper into this topic, feel free to check out this informative link

UPDATE

In Angular, consider utilizing $timeout instead of setTimeout. It can be implemented as follows:

$timeout(function(){
   console.log(array);
}, 0)

Answer №2

In JavaScript, the length property of an Array remains constant once set. You have two options for specifying the size of an Array: either by defining the number of properties it will contain like this: var a = new Array(2), or by simply passing in your values directly like so: var a = ['value1', 'value2'].

Answer №3

You are combining asynchronous and synchronous approaches in your code.

The Communications.find function is asynchronous, but you are using it synchronously in the getCommi function.

When you invoke the getCommi function, it immediately returns with an empty array.

To resolve this issue, make the following changes:

app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id, cb){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    } 
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    cb(null, array);
        });   
      }
  }
});

Additionally, update the following:

app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
getFoo.getCommi(3,1, function(err, emails){
  $scope.formModel.emails = [];
    for(var index=0; index < emails.length; index++){
        $scope.formModel.emails.push(emails[index]);
    }
});    
}])

DISCLAIMER: I am not familiar with AngularJS.

Answer №4

give this a shot:

showData(array[0].length)

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 trouble with object initialization in a jQuery GET request?

Looking to create an HTML button using jQuery that, upon clicking the chart button, will retrieve values from specified text inputs. These values will then be used to construct a JSON object which will subsequently be included in a GET request. $(".chart" ...

How can I retrieve the value from req.body following an AJAX POST request on the server side with Express?

Currently, I am utilizing AJAX to send JSON data: app.use(express.json()); app.use(bodyParser.urlencoded({extended:true})) app.use(express.urlencoded({ extended: true})); const rowObject=JSON.stringify(rowData) $.ajax({ type: "POST&q ...

The custom directive fails to display the value of {{variable}}

Here is the Angular controller setup: app.controller("timelineCtrl", function ($scope) { $scope.user="john"; . . . } This directive is also in place: app.directive('helloWorld', function() { return { ...

Revamping JSON structure by identifying id references

I recently attempted to update the city name within the JSON object provided below. "City":[ { "Name":"Delhi", "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd", "Towns":[ ...

What steps should be taken to link a frontend program on a separate port to a backend system?

Placing my frontend application in the public folder of a node.js application has allowed me to fetch form-data using the following request: try { await axios.post("/api/v1/contact-form", { name, email, msg, }); } My backend, ru ...

Show the message "Server is now active on port 5000" in the console but unfortunately cannot retrieve it

The backend API has a specific template that can be viewed here. Below is the code snippet for the backend: index.js import express from 'express'; import bodyParser from 'body-parser'; import mongoose from 'mongoose'; import ...

Unable to append DOM element using the node.insertBefore() method

I am facing an issue with a sorted list of items displayed alphabetically. My intention was to insert a corresponding letter from the alphabetArr array after each <li> element, using an id from the DOMElementsArr array. However, I seem to be missing ...

Tips for utilizing functions in JavaScript to convert temperature

Looking to create a Java Script code that converts temperature from Celcius to Fahrenheit using a function. How can I extract the value entered into the window.prompt and then use it for further temperature conversion in JavaScript? I have set up the HTML ...

What steps should I take to activate JavaScript type checking in Vue files within Visual Studio Code?

After much exploration, I have successfully configured Visual Studio Code to perform type checking for JavaScript within JS files. This feature highlights any bad code and provides explanations for why it is considered as such here. However, this function ...

What is the most effective way to trigger a jQuery datatable event after updates, rather than before?

After the default datatable updates like searching and sorting are finished, I am looking to update DOM elements. The issue is that the event listening currently fires before the actual sort or search completion. My goal is for my code to run after the s ...

React display

I've been working on a personal project and wanted to include a lottery wheel. I came across the 'lottery-wheel' package on npm, but unfortunately, my attempts to install and render it were unsuccessful. To install the package, I used the f ...

Leverage JavaScript Object Properties within Angular 5 Components

Here's a question I have on using ngx-charts in Angular 5. I am experimenting with ngx-charts to create a chart within my Angular 5 project. The code snippet for my component is shown below: import { Component, OnInit } from '@angular/core&ap ...

What is the most effective method for preserving RichText (WYSIWYG output)?

I am currently using a JavaScript-based rich text editor in my application. Could you suggest the most secure method to store the generated tags? My database is MySQL, and I have concerns about the safety of using mysql_real_escape_string($text);. ...

What is the best way to determine which events can be listened to on an EventEmitter?

If I have an object that inherits from EventEmitter, such as a stream or any other, is there a reliable method to determine all available events that can be listened to and identify all attached event listeners? While finding the attached event listeners ...

Exploring the implementation of ng-if directive with asynchronous data

I have encountered an issue where my ng-if is consistently evaluating to false. This makes sense since the data I am utilizing in my controller is obtained through an API response. My query is, how can I implement ng-if with asynchronous data? Here is the ...

Header sticks motionlessly when appearing, no animation when vanishing

edit: check out my sandbox https://codesandbox.io/s/nostalgic-morning-3f09m?file=/src/App.tsx I have a sticky header implemented in React/Gatsby that should become visible when the screen is scrolled to Y >= 420. Once it reaches this point, an animatio ...

Working with Angular: Retrieving a JSON value by using a dynamic key

I have a variable called param within the scope as $scope.param, which is always set to either foo or bar. I am constructing a table with rows defined by <tr ng-repeat="d in data">. When I use <td>{{d.foo}}</td> or <td>{{d.bar}}< ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...

Issue with React Js: Text Sphere not appearing on page reload

Currently immersed in a react.js environment and eager to incorporate this impressive animated text sphere. Utilizing the TagCloud package for rendering assistance, however, encountered an issue where the text sphere would only display once and disappear u ...

Encountering TypeError while attempting to assign an axios response to a data variable within a Vue component

Encountering the error message TypeError: Cannot set property 'randomWord' of undefined specifically at the line: this.randomWord = response.data.word; Confirming that console.log(response.data.word) does display a string. Vue Component Structu ...