I'm using an API to retrieve data on some stocks and I would like to add a column named symbol with the query values using the functon insertColumn but I'm getting an error (node:15732) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'result' of undefined.
I've tried changing let result to this.result and then do insertColumn.call(this), but the same error occurs. I thought it would be related with a closure error, but at this point I'm not sure
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 output goes 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
},...
and I want it to be 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
symbol: 'TSLA' //this would be changed once I change the query part as well
},
this.resulttoresult.. and why isinsertColumna function, remove the function, keep the code inside it - similarly with your(async () => {... remove that IIFE, kep its content - also,result[i].push({symbol: query});doesn't look right, sinceresult[i]is an object not an array