Javascript - Error encountered when utilizing a for loop to insert a new column into an array

I have been utilizing an API to fetch data on various stocks, and I am attempting to include a column named "symbol" with the query values using the function insertColumn. However, I am encountering an error message that says

(node:15732) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'result' of undefined
. I have made an attempt at modifying let result to this.result and then executing insertColumn.call(this), but unfortunately, the same error persists. Initially, I assumed it could be related to a closure error, but now I'm uncertain.

import ObjectsToCsv from 'objects-to-csv';
import yahooFinance from 'yahoo-finance2';



async function api(){

  const query = 'TSLA';
  const queryOptions = { period1: '2021-08-06', interval: "1d"};
  let result = await yahooFinance.historical(query, queryOptions);

    function insertColumn() {
      for (var i = 0; i < this.result.length; i++) {
        this.result[i].push({symbol: query});
      }
    };
    insertColumn();

  console.log(result);

  (async () => {
    const csv = new ObjectsToCsv(result);
    await csv.toDisk('C:/Users/Rafael Oliveira/Desktop/teste/test.csv');
  })();
};
api();

The current output looks something like this:

[
  {
    date: 2021-08-06T00:00:00.000Z,
    open: 711.900024,
    high: 716.330017,
    low: 697.630005,
    close: 699.099976,
    adjClose: 699.099976,
    volume: 15576200
  },...

However, my desired outcome is as follows:

[
  {
    date: 2021-08-06T00:00:00.000Z,
    open: 711.900024,
    high: 716.330017,
    low: 697.630005,
    close: 699.099976,
    adjClose: 699.099976,
    volume: 15576200
    symbol: 'TSLA' //this value will vary based on changes in the query part
  },

Answer №1

To enhance your code, it is recommended to utilize javascript's Array.prototype.map function to add a symbol to each item:

import ObjectsToCsv from 'objects-to-csv';
import yahooFinance from 'yahoo-finance2';

async function fetchData(){
  const query = 'TSLA';
  const queryOptions = { period1: '2021-08-06', interval: "1d" };
  const result = await yahooFinance.historical(query, queryOptions);
  const resultWithSymbol = result.map((item) => ({ ...item, symbol: query }));

  console.log(resultWithSymbol);

  (async () => {
    const csv = new ObjectsToCsv(resultWithSymbol);
    await csv.toDisk('C:/Users/Rafael Oliveira/Desktop/teste/test.csv');
  })();
};
fetchData();

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

Improving the efficiency of my conditions in a function with Vue JS

Does anyone have any suggestions on how to optimize this function? I feel like it could be shortened to improve its efficiency. Any help or advice would be much appreciated. Function: onStudentActionSelect: function () { if (this.selectedRows.length ...

Exploring the Possibilities with NodeJS and Socket.IO

I've encountered an interesting issue with my use of NodeJS and Socket.io. The server receives data through ZeroMQ, which is working perfectly fine. However, when there are a large number of connected clients (over 100), it appears that there is a de ...

The React component fails to render on the screen

Upon retrieving data from the database server, attempts to render it result in the data being shown in the console log but not displayed in the component. What could be causing this issue? useEffect(() => { readRequest().then(setTodos); c ...

Changing the templateUrl of a directive on the fly using the controller

How can I dynamically pass the templateUrl for the app_modal directive from the "ServerController" controller to allow for different templates for different modals? I have included the URL as an attribute in the "app-modal" tag used in the server_group.htm ...

Unlocking new possibilities with Passport.js - sharing tokens across multiple servers

Currently, I am utilizing passport.js and MongoDB to handle user login and postAPI authentications. However, every time I deploy my node server to a different AWS instance, I find myself having to go through the signup process, log in, and obtain a new tok ...

Guide to correctly selecting <i> tags within a <p> tag using jQuery

I'm attempting to retrieve the text from the i (italic) elements within a paragraph using this code: $('p').each(function(j, element){ if($(element).is("i")){ console.log("The value is: "+$(element).text()); } }); However, ...

Eliminate the div element using jQuery if it contains a line break tag but no text

I am faced with a situation on a page where some div elements contain content while others only have a BR tag. I am attempting to remove the div elements that contain only the BR tag. Below is the HTML format in question: Here is an example of one type: ...

How come my uvmapped texture is flipping vertically when using iewebgl + threejs?

Currently in the process of developing a 3D viewer for game pads with the aim of customizing the pad using various colors and materials. Initially, I created a simple ".bin .js" loader with sample materials using Threejs r62 to create a visualizer prototy ...

Refresh ng-repeat array after implementing filter in controller

I am currently facing an issue with updating my table view when changing a variable that filters an array. The filter is applied in the controller based on the values of a specific variable called columnFilter. However, the filter does not reapply to updat ...

npm package.json scripts not executing

Whenever I try to run npm start or npm run customScriptCommand, npm seems to not be executing anything on my project and just quickly returns a new line in the terminal. I attempted to solve this issue by uninstalling node and npm from my machine, then in ...

Prisma auto-generating types that were not declared in my code

When working with a many-to-many relationship between Post and Upload in Prisma, I encountered an issue where Prisma was assigning the type 'never' to upload.posts. This prevented me from querying the relationship I needed. It seems unclear why P ...

Using HTML and JavaScript to create a link that appears as a URL but actually directs to a JavaScript function

I am working on an HTML page and I am trying to create a link that appears to go to 'example.html' but actually goes to 'javascript:ajaxLoad(example.html);'. Here is what I have tried: <a href="example" onclick="javascipt:ajaxLoad( ...

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

Unable to Trigger Virtual Click Event on Calendar in JavaScript

My workplace utilizes a custom web application with a date picker/calendar that I am attempting to modify programmatically. The app is built in Vue, which has added complexity to my task. Despite exhaustive efforts, I have been unable to select or inject d ...

I can't seem to figure out why this isn't functioning properly

Upon examining the script, you'll notice the interval() function at the very bottom. The issue arises from bc-(AEfficiency*100)/5; monz+((AEfficiency*100)/5)((AFluencyAProduct)/100); For some reason, "bc" and "monz" remain unchanged. Why is that so? T ...

Leveraging PHP JSON responses for decision-making in jQuery/JavaScript

Recently, a friend shared the following code snippet with me: json : { result: true } success function(data){ if(data.result) { //do something here } else { //do something here } } I'm curious how I can integrate that ...

What is the best way to include a new class into the current class in this particular scenario?

Just starting out with Javascript and Jquery, so please bear with me if this question seems basic I'm dynamically constructing HTML like this: var favoriteresultag = '<ul>'; favoriteresultag += "<section id='"+name+"' ...

Error in Node.js: Trying to access the 'body' property of an undefined variable

While working on a project for a Udacity course, I encountered a stumbling block. The issue revolves around capturing user input from a form and making a post request to return a javascript object. However, when attempting to run the server with node js, I ...

Using three.js to retrieve the camera's position using orbit controls

In my journey using three.js orbit controls, I have encountered a challenge of making a skybox follow the camera's position. Despite scouring the internet, I have not come across a suitable solution. My query is straightforward - how can I obtain the ...

What steps can you take to address Git conflicts within the yarn.lock file?

When numerous branches in a Git project make changes to dependencies and use Yarn, conflicts may arise in the yarn.lock file. Instead of deleting and recreating the yarn.lock file, which could lead to unintended package upgrades, what is the most efficie ...