我需要訪問的API的最后一個月的資料,但我不知道我怎么能訪問的第二個物件,沒有硬編碼像這樣的日期:
const data = [data.data['Monthly Time Series']['2021-11-30']]。在這個例子中,目前我需要來自“每月時間序列”的 11 月資料,但我需要它是動態的而不是寫出日期,所以它總是會顯示過去一個月的實際資料。我將不勝感激任何幫助。
這是 JSON 的樣子:
{
"Meta Data": {
"1. Information": "Monthly Prices (open, high, low, close) and Volumes",
"2. Symbol": "IBM",
"3. Last Refreshed": "2021-12-08",
"4. Time Zone": "US/Eastern"
},
"Monthly Time Series": {
"2021-12-08": {
"1. open": "118.2500",
"2. high": "123.3800",
"3. low": "116.5600",
"4. close": "123.0200",
"5. volume": "33320654"
},
"2021-11-30": {
"1. open": "125.0500",
"2. high": "127.2900",
"3. low": "114.5600",
"4. close": "117.1000",
"5. volume": "119252012"
},
uj5u.com熱心網友回復:
這可能看起來有點復雜,但它絕對會為您提供每月條目的最后日期
let data = {
"Meta Data": {
"1. Information": "Monthly Prices (open, high, low, close) and Volumes",
"2. Symbol": "IBM",
"3. Last Refreshed": "2021-12-08",
"4. Time Zone": "US/Eastern"
},
"Monthly Time Series": {
"2021-12-08": {
"1. open": "118.2500",
"2. high": "123.3800",
"3. low": "116.5600",
"4. close": "123.0200",
"5. volume": "33320654"
},
"2021-11-30": {
"1. open": "125.0500",
"2. high": "127.2900",
"3. low": "114.5600",
"4. close": "117.1000",
"5. volume": "119252012"
}
}
}
console.log(
data["Monthly Time Series"]
[Object.keys(data["Monthly Time Series"])
[Object.keys(data["Monthly Time Series"]).length - 1]]) // This gets you the last entry
uj5u.com熱心網友回復:
您可以使用Object.values()來獲取每月時間序列值的陣列。
一旦我們有了monthlyTimeSeries,我們就可以使用標準陣串列示法 ([1]) 獲得第二項:
let obj = { "Meta Data": { "1. Information": "Monthly Prices (open, high, low, close) and Volumes", "2. Symbol": "IBM", "3. Last Refreshed": "2021-12-08", "4. Time Zone": "US/Eastern" }, "Monthly Time Series": { "2021-12-08": { "1. open": "118.2500", "2. high": "123.3800", "3. low": "116.5600", "4. close": "123.0200", "5. volume": "33320654" }, "2021-11-30": { "1. open": "125.0500", "2. high": "127.2900", "3. low": "114.5600", "4. close": "117.1000", "5. volume": "119252012" } } }
const monthlyTimeSeries = Object.values(obj["Monthly Time Series"]);
const result = monthlyTimeSeries[1];
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
嘗試
var result = Object.entries(data['Monthly Time Series'])
console.log(result);
將給出以下結果
[
[
'2021-12-08',
{
'1. open': '118.2500',
'2. high': '123.3800',
'3. low': '116.5600',
'4. close': '123.0200',
'5. volume': '33320654'
}
],
[
'2021-11-30',
{
'1. open': '125.0500',
'2. high': '127.2900',
'3. low': '114.5600',
'4. close': '117.1000',
'5. volume': '119252012'
}
]
]
您可以通過此串列進行映射以獲取所需日期的資料
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/384552.html
標籤:javascript 接口 目的
