Saving to an object in a loop using square brackets does not impact the object in any way

In this function, I am working with a mongo cursor called resources. My goal is to restructure these resources by creating an empty object and utilizing bracket notation to store the resources. However, it seems that my simplified code is exhibiting unexpected behavior.

It's puzzling why Mongo would be affecting the outcome here, especially since typeof r.id === string. This issue becomes even more perplexing because when I employ .forEach on a different data structure, everything works as expected.

Just to note, I am writing in Typescript.

const restructured_resources = async(resources: any, db: any) => {
    
    let restructured_resources: any = {}
    resources.forEach((r: any) => {
        const id = r.id
        restructured_resources[id] = "yo"
    })

    console.log(restructured_resources) //{}

})

Answer №1

By introducing the await keyword before the forEach function, I noticed that the object starts populating with the expected key value pairs. This made me realize that looping through a Mongo cursor using a forEach loop is not a typical synchronous operation and seems to be queued after the console.log statement.

const updated_resources = async(resources: any, db: any) => {

    const thing: any = {}
    await resources.forEach((resource: any) => {
        updated_resources[resource.id] = "yo"
    })

    console.log(updated_resources)

Answer №2

If this code doesn't seem to be working, it could be due to an issue related to asynchronous processing.

const updatedData = (data) => {
  let updatedData = {}
  data.forEach((d) => {
    const key = d.key
    updatedData[key] = "value"
  })

  console.log(updatedData) //{}

}

updatedData([{key: 'A'},{key: 'B'},{key: 'C'},{key: 'D'},{key: 'E'},]);

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

Acquire a numerical value from a text source and increment it by one using Jquery

I have a simple task of extracting a single number from a particular div. Once obtained, I intend to increment the number by one. However, despite successfully retrieving the number, my attempts to add one to it are not working as expected. For example: ...

Update an existing item or add a new one if it is not already present

I am attempting to create a functionality similar to canva.com, where users can select images from the sidebar and drop them anywhere in the "div", allowing multiple images with individual positions. However, when I use setState(prevState=>{return [...p ...

the pause in execution before my function redirects to a different route

Currently, I am developing a page using nodeJs with express which is supposed to display a table. However, I encountered an issue with my variable "allMusique" that contains the data for my page. When trying to access it initially, there seems to be an err ...

React Infinite Scroll - Issue with Intersection Observer API causing constant jumping back to the top

I am currently working on a React application that implements infinite scrolling using the Intersection Observer API without relying on any third-party libraries. My backend system is properly set up for pagination, and the infinite scrolling feature succe ...

Tips on sorting content by tag instead of by heading

Hello, I am new to programming and seeking some advice regarding a piece of code that I am trying to understand and fix in hubSpot. My goal is to modify the code so that it can search blog posts based on tags rather than just the title. Any guidance or t ...

Combining Power BI with Spring Angular for Seamless Integration

I am in the process of building a web platform with Spring and Angular. One important element I want to include is Power Bi integration, allowing me to generate datasets and reports using Spring and display charts in Angular. Are there any resources or t ...

The proper method for retrieving FormData using SyntheticEvent

I recently implemented a solution to submit form data using React forms with the onSubmit event handler. I passed the SyntheticBaseEvent object to a function called handleSubmit where I manually extracted its values. I have identified the specific data I n ...

Guide on setting up the installation process of Gulp jshint with npm?

Having trouble with the installation of JSHint. Can anyone point out what I might be doing incorrectly? This is the command I am using: npm install --save-dev gulp-jshint gulp-jscs jshint-stylish Getting the following error message: "[email protect ...

Unable to resolve all parameters for the RouterUtilities class

My goal is to develop a RouterUtilities class that extends Angular's Router. Despite the app running and compiling smoothly, when I run ng build --prod, it throws an error message like this: ERROR in : Can't resolve all parameters for RouterUtil ...

Ways to incorporate onload animation into a Pie chart with billboard js

I am currently working on implementing a pie chart with animation using billboard js. However, I am facing difficulties in applying the onload animation. Can anyone provide guidance on how to achieve this? For reference, you can view an example of the des ...

Implementing a Masonry layout within an ASP UpdatePanel

I have an ASP-WebPage where I'm using an UpdatePanel with a Dropdown and Output-Div for dynamically generated Cards. These cards are layouted by Masonry. The content of the Output-Div is bound to the Dropdown selection. Initially, the Masonry-Layout ...

The 'validate' property within the 'MappingService' class cannot be assigned to the 'validate' property in the base class 'IMappingService' in typescript version 2.8.0

Currently, I am utilizing the AngularJS framework (version 1.5.8) in tandem with the latest TypeScript files (2.8.0). However, upon updating to the newest version of TypeScript, the code below is failing to compile. The IMappingService interface: export ...

Solving issues with Angular4 Router changes

I'm attempting to chain the router resolver for my application. Below are my Router options: { path: '', component: AdminComponent, resolve: [ SessionResolve, LocaleResolve ] } The desired flow is to first call S ...

Need assistance with filling the space between two vertical lines on a chart using the chartjs library?

Can someone help me figure out how to fill the area between two line graphs using chartjs? I know how to do it when one line is on top of the other, but I'm struggling with getting the area between two lines that are side by side. For example, I&apos ...

Is there a way to dynamically alter the content depending on the index of the current slide using swiper.js?

Hi, I am new to utilizing the Swiper framework and so far, it has been one of the best sliders I have ever experienced. Currently, I am trying to establish a connection between 2 div tags - one tag holds the content of each slide while the other tag contro ...

Group by the sum of the modulus values and return the result

I am in need of calculating the sum of results of a query grouped by a certain field. Let me illustrate this with an example. Here are the results of the find() query: { "_id" : ObjectId("5749a5fd7aed9ced75b94218"), "groupValue" : "5", "weight" : 123 } { ...

Sending a file through an Ajax POST request to a PHP server

I am attempting to upload the HTML input file to my PHP file using a different method than the traditional synchronous HTML forms. The problem I am encountering is that it seems like I am not correctly POST'ing the input file to my PHP file because t ...

Exploring the depths of nested object arrays and navigating through historical indexes

I am working with nested object arrays within an array and looking to determine the path of a specific key. For instance: const dataList = [ [ [{id: 100,name: 'Test1'}, {id: 120,'Test12'}], [{id: 101,name: 'Test1&apo ...

Exploring the Interplay of Classic ASP and AJAX Variables References

When the page loads, I check for an empty session variable. If it is empty, I trigger an AJAX function to include a hidden login form with ASP script that becomes visible through JavaScript. This part of the process works smoothly. Upon submitting the for ...

Integrate new HTML elements into the React component structure

Is there a way to seamlessly add a DOM element using vanilla javascript into a hierarchy of DOM nodes generated by React without it being removed when the state updates? Motivation: I am working on a browser extension and aiming to closely integrate with ...