Google Apps Script报错解决:如何从嵌套对象提取所有股息值
问题解决:提取雅虎财经股息值时的TypeError错误
问题描述
尝试从雅虎财经API返回的对象中提取所有股息值,运行代码时出现错误:TypeError: obj.chart.result[0].events.dividends.map is not a function
原代码:
function test() { var url = "https://query1.finance.yahoo.com/v8/finance/chart/VZ?formatted=true&lang=en-US&region=US&interval=1d&period1=1451624400&period2=1672963200&events=div&useYfid=true&corsDomain=finance.yahoo.com"; var obj = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText(); var obj = JSON.parse(obj); var dividend = obj.chart.result[0].events.dividends.map(o => (({ o: { amount } }) => amount)); console.log(dividend) }
错误原因
雅虎财经API返回的dividends是键值对形式的对象(键为时间戳,值为包含股息信息的子对象),而非数组。map是数组的专属方法,对象没有这个方法,因此调用时会抛出TypeError。另外原代码的箭头函数写法错误,嵌套了不必要的函数,无法正确提取值。
修改后的代码
function test() { var url = "https://query1.finance.yahoo.com/v8/finance/chart/VZ?formatted=true&lang=en-US&region=US&interval=1d&period1=1451624400&period2=1672963200&events=div&useYfid=true&corsDomain=finance.yahoo.com"; // 获取并解析API返回内容 var response = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText(); var obj = JSON.parse(response); // 容错检查:确保各层级结构存在 if (!obj?.chart?.result?.[0]?.events?.dividends) { console.log("未找到股息数据"); return; } // 将dividends对象转为数组,再提取amount值 var dividends = Object.values(obj.chart.result[0].events.dividends) .map(item => item.amount); console.log(dividends); }
关键修改解释
- 对象转数组:使用
Object.values()方法,把dividends对象的所有值提取出来转换成数组,这样就能使用map方法遍历。 - 修正箭头函数:直接在
map的回调中提取每个子对象的amount属性,避免不必要的函数嵌套。 - 增加容错处理:用可选链操作符
?.检查各层级结构是否存在,防止因API返回结构变化或无数据时出现报错。
内容的提问来源于stack exchange,提问作者Newbie
相关产品推荐
相关产品推荐

