What is the most efficient way to iterate through an array and retrieve the values of each item in it?

I'm trying to iterate through an array of objects and retrieve all the data from each object, but for some reason, I'm only getting the data from the last object. Can anyone help me figure out why it's skipping the first one?

Here is the array I'm working with:

item {
  _id: new ObjectId("627ed71261b2bd692178bdca"),
  sn: 'fN300W15076fd5bg6dwf',
  merchantId: '9000000058800',
  merchantName: '999',
  networkType: '220509',
  __v: 0,
  terminalId: '987654321',
  resultData: [
    // data for multiple objects within the array
  ]
}
----------------------------------------------------
// More items with their respective data

Despite having multiple objects in the array, I'm only able to access the resultData from the last object.

If you're curious about my code implementation, here is how it looks:

  async getLogByTPE() {
    let result;
    // Code logic for retrieving and processing data
  }

In this function, I aim to fetch the resultData from each object within the array, but I seem to be stuck only accessing the data from the last object. Any insights or assistance would be greatly appreciated!

Answer №1

Each time the loop runs, the result variable is overwritten, leading to only the last value being stored when you return. To solve this issue, one way is to initialize an empty array for the result variable:

  let result: any = [];

Then, within the loop, you can add items to this array by using result.push(item.resultData); instead of result = item.resultData;.

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

Leveraging the power of $lookup and $mergeObjects in aggregation

I'm looking to join a collection. Previously, I used only lookup to get separated fields that are joined, but now I need the results similar to MySQL join. I have tried using $lookup and $mergeObjects for this action, but they are not working well. H ...

Resolving parent routes in Angular 2

I am encountering an issue with my code. The 'new' route is a child route for the 'users' route. The 'users' route has a resolver, and everything works fine up to this point. However, after successfully creating a new user, ...

Traversing a nested array using jQuery

I'm attempting to utilize jQuery's each function in order to iterate through the provided array. My aim is to identify the key ("Name") and display its corresponding array values on the webpage. Array ( [E-mail] => Array ( ...

Angular routing within a modal box

I currently have two functioning routes: app.config(['$routeProvider', '$locationProvider', function( $routeProvider, $locationProvider) { $routeProvider. when("/list/:class", { controller: "listController", t ...

Keep sensitive information confidential by refraining from displaying values in the URL while using

When attempting to log in using Spring Security with an AJAX call, I noticed that the username and password are being displayed in the URL. For example: /?j_username=s&j_password=s I have been trying to identify my mistake for quite some time now but ...

Using Vuetify to send a parameter from a select option to a method as a parameter

Just starting out with vuejs and encountering an issue passing parameters from a selected option to my JavaScript method. In my updateClientIsMaster method, the item is always undefined. However, when I added v-on:change="updateClientIsMaster in the & ...

Send pages to the holding page first before redirecting them to the appropriate page on the new website

I am in the process of updating my old website (www.old.com) with a new one that has similar pages (www.new.com). I want all the pages from www.old.com to automatically redirect to a temporary holding page (a basic html page with a countdown script and red ...

Is there a way for me to access the source code of elements within React Native?

Currently, I am working on writing code using React Native and compiling it in Android Studio with an emulator. When I press ctrl+m on the emulator and select "show inspector" to click on elements, I am unable to see which line of code corresponds to the s ...

Embedding external javascript within another javascript file

I have two pieces of code - code 1 and code 2. Code 1 is login.html which I am saving as login.js, and code 2 consists of some jQuery and JavaScript codes. My problem is how to insert the first code into the second code. Code 1: login.html (saved as logi ...

NextJS project utilizing the power of Typescript and composite structure

I recently revamped my NodeJS/Typescript project using workspaces and project references. Within one of the workspaces, I have a NextJS application with a recommended tsconfig.json configuration property: "noEmit": true However, this setting con ...

Tips for troubleshooting 'npm ERR! 403: The requested package version is not permitted by your security policy. Typically, this issue arises when you or one of your dependencies are attempting to access a restricted package version.'

Currently, I am in the process of setting up a Jenkins and a private npm repository called Sonatype Nexus. I am encountering an error when attempting to publish to the repository within a Jenkins build pipeline. + npm publish --registry https://<my-priv ...

The issue of Chrome not updating when resizing the window in jQuery

I've encountered an issue while using jQuery to obtain the height of a specific element, as this measurement changes when someone resizes their browser window. Below is the code snippet I am currently using: $(function() { var wheight = $('. ...

What is the method to retrieve the current index of an item in v-carousel?

My current code successfully cycles a carousel, but I would like to display the item title underneath the image instead of on top. I believe creating a new data value that updates with each change in the carousel is the solution. However, I am struggling ...

Ways to determine if a JSONArray Element is empty

I am struggling to determine whether an element within a JSON array is null. When checking if the jsonObject itself is null, I can simply use: jsonObject.isNullObject(); However, when dealing with an array and trying to check if a specific element inside ...

Pulling JavaScript - referencing an external script

I am currently facing a challenging dilemma that requires a simple yet intricate solution. My objective is to develop a script capable of playing chess on my behalf, utilizing an engine to determine the optimal moves for pieces such as rooks, bishops, king ...

Issues arise while utilizing the execute method in PHPUnit-Selenium2

When creating Acceptance tests with PhpUnit and its Selenium2 extension, I am attempting to utilize the execute method within the PHPUnit_Extensions_Selenium2TestCase class to run Javascript code that checks if the document is fully loaded. Here is an exa ...

Jquery pop-up information bubble

I'm currently using: jQuery Bubble Popup v.2.3.1 http://maxvergelli.wordpress.com/jquery-bubble-popup/ The following code should be included within the document ready section: $('.bubble').CreateBubblePopup({ align: 'cent ...

Unable to locate the JavaScript script file referenced in the HTML document

I am having an issue with referencing the javascript file "doggies.js" in the basket folder on my website. Every time I click a button, it says the file cannot be found. I've tried using ../doggies.js as well, but that didn't work either. Is ther ...

Updating code to insert elements into an array/data structure using Javascript

Hey everyone, I'm new to Javascript and I'm trying to make a change to some existing code. Instead of just returning the count of elements, I want to add each of the specified elements to an array or list. Here is the original code from a Seleni ...

The React-loadable alert indicated a discrepancy in the text content

Utilizing react-loadable for dynamic JS module loading is part of my process. With server-side rendering already set up and functioning correctly for react-loadable, I am encountering an issue on the client side. Upon page load, a warning message appears i ...