I'm trying to pull raw data from dynamically named objects from Yahoo Finance. In the following simplified example codes, I hard coded its object key name and index after manually checking its object structure to retrieve raw data. Instead of such a hard coding which will be really difficult if more than 100 keys, I'm looking for a smart solution that checks all the object keys and pull their raw data from them directly without needing to write each key names manually. How can I do that? Thanks!
My expected output:
function test() {
var url = 'https://query2.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/AVGO?lang=en-US®ion=US&symbol=AVGO&padTimeSeries=true&type=annualInterestExpense,trailingInterestExpense&merge=false&period1=493590046&period2=1672807102&corsDomain=finance.yahoo.com';
var obj = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
obj = JSON.parse(obj); //Convert strings to object
var type = obj.timeseries.result.map(({ meta: { type } }) => type).flat();
console.log(type)
var trailingInterestExpenseRAW = obj.timeseries.result[0].trailingInterestExpense.map(({ reportedValue: { raw } }) => raw);
var annualInterestExpenseRAW = obj.timeseries.result[1].annualInterestExpense.map(({ reportedValue: { raw } }) => raw);
console.log(['trailingInterestExpense', ...trailingInterestExpenseRAW],
['annualInterestExpense', ...annualInterestExpenseRAW])
}
CodePudding user response:
In your script, how about the following modification?
From:
var type = obj.timeseries.result.map(({ meta: { type } }) => type).flat();
console.log(type)
var trailingInterestExpenseRAW = obj.timeseries.result[0].trailingInterestExpense.map(({ reportedValue: { raw } }) => raw);
var annualInterestExpenseRAW = obj.timeseries.result[1].annualInterestExpense.map(({ reportedValue: { raw } }) => raw);
console.log(['trailingInterestExpense', ...trailingInterestExpenseRAW],
['annualInterestExpense', ...annualInterestExpenseRAW])
To:
var types = obj.timeseries.result.flatMap(({ meta: { type } }) => type);
var array = obj.timeseries.result.map(o => types.flatMap(type => o[type] ? [type, ...o[type].map(({ reportedValue: { raw } }) => raw)] : []));
var maxLen = Math.max(...array.map(r => r.length));
var values = array.map(r => [...r, ...Array(maxLen - r.length).fill(null)]);
console.log(values); // You can see the values in the log.
// In this sample, the values are put to the active sheet.
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(sheet.getLastRow() 1, 1, values.length, values[0].length).setValues(values);
- When this script is run,
values
is[["trailingInterestExpense",1737000000,null,null,null],["annualInterestExpense",1444000000,1777000000,1885000000,1737000000]]
. By this, this value can be put to the sheet usingsetValues
.