Key of object is not defined

When I receive an object from an API, I am creating new objects inside it using other API responses. For example:

API Response 1: Obj: {a: 1, b: 2}

API Response 2: 3

Creating an object: Obj.c = 3

Final result: Obj: {a: 1, b: 2, c: 3}

Issue:

console.log(Obj) returns Obj: {a: 1, b: 2, c: 3}

console.log(Obj.c) returns undefined

After using .map on the properties and trying to access the created properties with a console.log, they return undefined. However, when logging any object, the created properties are present.

My Code:

async getGeneralInfo(token, seed) {
    try {
        API_HEADER.headers.Authorization = token;
        let responseAvaliableCoins = await axios.get(
            BASE_URL + "/coin",
            API_HEADER
        );

        let avaliableCoins = responseAvaliableCoins.data.data.coins;

        avaliableCoins.map(async (coin, index) => {
            if (coin.status === "active") {
                let responseCreateAddress = await axios.post(
                    BASE_URL + "/coin/" + coin.abbreviation + "/address",
                    { seed },
                    API_HEADER
                );

                avaliableCoins[index].address =
                    responseCreateAddress.data.data.address;

                let responseBalance = await axios.get(
                    BASE_URL +
                    "/coin/" +
                    coin.abbreviation +
                    "/balance/" +
                    coin.address,
                    API_HEADER
                );

                avaliableCoins.token = responseBalance.headers[HEADER_RESPONSE];
                avaliableCoins[index].balance = responseBalance.data.data;
            } else {
                avaliableCoins[index].address = undefined;
                avaliableCoins[index].balance = undefined;
            }
        });

        console.warn(avaliableCoins[0].balance); //undefined
        console.warn(avaliableCoins[0]["balance"]); //undefined
        console.warn(avaliableCoins[0].address); //undefined
        console.warn(avaliableCoins[0]["address"]); //undefined

        console.warn("avaliableCoins", avaliableCoins); //All objects are here
        console.warn("avaliableCoins[0]", avaliableCoins[0]); //All objects are here

        return avaliableCoins;
    } catch (error) {
        internalServerError();
        return;
    }
}

update ----- https://i.sstatic.net/Glx4Z.png

Answer №1

The function utilized within the map operation is asynchronous.

Currently, when map is invoked on all coins, the subsequent code progresses to the console.warn() statements before all asynchronous data has been retrieved.

availableCoins will be eventually updated with the asynchronously fetched data; however, a race condition exists as the code does not explicitly wait for this update to occur.

Consider the following recommended approach:

  • Enhance each item returned from an async call within map. This generates a Promise that resolves to the modified item post-completion of the async operation.
  • Employ Promise.all() to await the array of generated Promises.
  • Return the resultant array upon completion of all operations.

A simplified demonstration showcasing the proposed approach appears below:

const fetchData = () => {
  return Promise.resolve('data');
}

export const fetchGeneralInfo = async () => {
  let availableCoins = [
    { a: 1 },
    { a: 2 }
  ]

  const promises = availableCoins.map(async (coin) => {
    let response = await fetchData();
    // Modify 'coin' and return it
    coin.data = response;
    return coin;
  });

  const updatedCoins = await Promise.all(promises);

  console.log(updatedCoins); // [{a: 1, data: 'data'}, {a: 2, data: 'data'}]

  return updatedCoins;
}

Your updated function would resemble the following:

async fetchGeneralInfo(token, seed) {
  try {
    API_HEADER.headers.Authorization = token;
    let responseAvailableCoins = await axios.get(
      BASE_URL + "/coin",
      API_HEADER
    );

    let availableCoins = responseAvailableCoins.data.data.coins;

    const promises = availableCoins.map(async (coin) => {
      if (coin.status === "active") {
        let addressResponse = await axios.post(
          BASE_URL + "/coin/" + coin.abbreviation + "/address",
          { seed },
          API_HEADER
        );

        coin.address =
          addressResponse.data.data.address;

        let balanceResponse = await axios.get(
          BASE_URL +
          "/coin/" +
          coin.abbreviation +
          "/balance/" +
          coin.address,
          API_HEADER
        );

        coin.token = balanceResponse.headers[HEADER_RESPONSE];
        coin.balance = balanceResponse.data.data;
      } else {
        coin.address = undefined;
        coin.balance = undefined;
      }
      return coin;
    });

    availableCoins = await Promise.all(promises);

    console.warn(availableCoins[0].balance); //undefined
    console.warn(availableCoins[0]["balance"]); //undefined
    console.warn(availableCoins[0].address); //undefined
    console.warn(availableCoins[0]["address"]); //undefined

    console.warn("availableCoins", availableCoins); //All objects are present
    console.warn("availableCoins[0]", availableCoins[0]); //All objects are present

    return availableCoins;
  } catch (error) {
    internalServerError();
    return;
  }
}

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

Utilizing the LitElement component multiple times within a single webpage

Developed a web component using LitElement which is being utilized multiple times on the same page. Looking to initiate a single event when the component is rendered for the first time on the page. ...

What is the best way to manage CSS while working with Node.js?

I am experimenting with pure vanilla Node.js without any additional frameworks for educational purposes. Currently, I have the following setup: var fs = require('fs'), jade = require('jade'); function compile(dirPath, res) { var ...

Every time I attempt to iterate through an array, it behaves as if it were a set. This means that adding two identical values causes the program to abruptly stop running

I'm currently working on an AngularJS program where I need to iterate through an array. Below is the code snippet: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">&l ...

Having trouble with installing my personal npm package

Recently, I have been working on an Open Source project with Node as a CLI tool that is set to be released soon. While testing the CLI on another project, I faced an issue. Even though I installed the project globally using npm install -g without any error ...

Verifying the presence of objects within a JSON Array in a Logic App

I'm currently experimenting with this, but I haven't been able to make it work successfully. Within a Condition connector, the code I am using is as follows: @contains(json(body('ParseCustomerDeltaXML')).newMembers[0], 'Member&ap ...

How to send a contact form in Wordpress with multiple attachments via email without using any plugins

The main objective is to enable users to submit their own content for new articles (including text and files) to the administrator's email. A form has been created for this purpose: <form class="form form-send" enctype="multipart/fo ...

Ways to update the canvas every x seconds

Is there a way to automatically update my canvas every x seconds without having to reload the entire page? <script> $(document).ready(function () { var odo = new RGraph.Odometer({ id: 'cvs', min: 0, max: 360, ...

PHP encountered an issue when retrieving a value from a URL and passing it to a JavaScript variable

How can I pass a PHP variable from the URL using $_REQUEST to JavaScript in order to send it through Ajax? Here is the code snippet at the top of my page: <?php include_once('../php/connection.php'); include_once('../php/getDiagnosi ...

Send data to local REST service with Jquery/Ajax for file upload

I am currently trying to implement a REST service that allows me to upload files to our database using the file explorer. So far, I have successfully managed to open the file explorer by clicking on my findDocumentOnboarding button within an input type="fi ...

Struggling to update a Knockout observable array

I'm attempting to send some data to a Knockout observable array. Despite receiving data from my AJAX call without any errors during script execution, I find that the userNames array remains empty when accessed. What could be causing this issue? UserH ...

Mapping FuelPHP routes to Angular routes

Currently, my application has routes and request handling mechanism implemented in FuelPHP for calculating templates on the server side. From what I have observed, processing templates on the server side tends to be slower. Therefore, I am interested in t ...

What are some effective methods for slicing arrays?

I have two 9x9 arrays that I want to convert into a 9x3 array by rearranging the values along the diagonal and off-diagonals. My approach involves treating the arrays as 3x3 "blocks" and extracting the desired values using either a for loop or list compreh ...

Transferring JSON data using $.post in Express/NodeJS

Below is the contents of my app.js file: var express = require('express'); var app = express(); var path = require('path'); var $ = require('jquery'); var nodemailer = require('nodemailer'); app.use('/static&a ...

Tips for incorporating theme colors in the "color" prop when employing MaterialUI components

Trying to utilize the colors from my Mui palette as values for the color property in this way: For example: <Tabs indicatorColor="primary.mainGradient" > <Tab /> </Tabs> However, this approach does not seem to wo ...

Using JavaScript to manipulate CSS Keyframes

Can I control these animations with JS/JQuery instead of CSS hover action? .button { width: 350px; height: 300px; margin: 100px auto; position: relative; border: solid 2px #cbd4d9; -webkit-border-radius: 5px; -moz-border-radius: 5px; bor ...

When using QML, functions like Object.keys, Object.values, and JSON.stringify may return unexpected empty results

I have written a code that exposes a C++ object to QML, and I want to verify the declared properties of the object using native JS methods. However, they are not working as expected. I created a method called FizzBuzzDerived.properties, which functions cor ...

What is the best way to incorporate all images from the resources into an array using VB?

I am a beginner in VB programming and coding overall. I am currently facing some challenges in attempting to create an image array from the pictures stored in Resources. I believe this can be achieved through a loop, but I am unsure of how to do it... Ap ...

Valgrind uncovers an astonishing amount of improper writes and reads

Seeking a deeper understanding of valgrind, I am puzzled by the numerous invalid writes and reads detected by valgrind in one of my C programs. The issue arises with an invalid write reported for a function call where the pointer and array have been alloca ...

The Java program for user input arrays is currently only collecting three integers instead of the expected five

This specific code snippet is designed to take in 5 user integers, display them, and then print them out in reverse order. However, the current behavior is that it only captures the first integer input, repeats it thrice, and then repeats the same intege ...

Angular response object being iterated through in a loop

I am facing a challenge while trying to iterate through an array containing values that need to be displayed to the user. Despite receiving a response with the data, I am having trouble accessing and looping through the elements of the array using Angular. ...