json API响应未定义[重复]

nnt7mjpx  于 2023-11-20  发布在  其他
关注(0)|答案(2)|浏览(91)

此问题在此处已有答案

How do I loop through or enumerate a JavaScript object?(48个回答)
How to access the first property of a Javascript object?(23个回答)
三年前就关门了。
当我试图访问数据的第0个索引时,我得到了错误undefined,但当我试图打印出整个对象时,它工作正常。我无法访问任何元素或循环数据。data变量工作正常,但tSeries变量未定义。
这是一段代码:

var data;
var tSeries;


(async () => {
    const response = await fetch("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=" + key);
    apidata = await response.json();
    data = (apidata["Meta Data"]["2. Symbol"]);
    tSeries = (apidata["Time Series (Daily)"][0]);
    console.log(tSeries);
    
})();

字符串
下面是JSON响应代码:

{
    "Meta Data": {
        "1. Information": "Intraday (5min) open, high, low, close prices and volume",
        "2. Symbol": "IBM",
        "3. Last Refreshed": "2020-06-24 16:00:00",
        "4. Interval": "5min",
        "5. Output Size": "Compact",
        "6. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2020-06-24 16:00:00": {
            "1. open": "116.4600",
            "2. high": "116.6700",
            "3. low": "116.3800",
            "4. close": "116.4900",
            "5. volume": "263785"
        },
        "2020-06-24 15:55:00": {
            "1. open": "116.8000",
            "2. high": "116.8600",
            "3. low": "116.3500",
            "4. close": "116.4700",
            "5. volume": "154646"
        },
        "2020-06-24 15:50:00": {
            "1. open": "117.0100",
            "2. high": "117.1400",
            "3. low": "116.8500",
            "4. close": "116.8500",
            "5. volume": "99465"
        },
        "2020-06-24 15:45:00": {
            "1. open": "116.6900",
            "2. high": "117.0400",
            "3. low": "116.6600",
            "4. close": "117.0100",
            "5. volume": "83736"
        }

juzqafwq

juzqafwq1#

那样行不通的
你可以做apidata["Time Series (Daily)"]["2020-02-03"]
获取日期的特定对象,或者您可以使用map/reduce/filter来获得所需的结果。

Object.values(apidata["Time Series (Daily)"]).map((value, index) => console.log(value));

字符串
或者对于钥匙:

Object.keys(apidata["Time Series (Daily)"]).map((key, index) => console.log(key));


但是你可以用你从那里得到的值做任何你想做的事情。

j9per5c4

j9per5c42#

第一个月
应该可以。
或者,您可以将这些日常对象放在数组上,然后选择第一个对象。

相关问题