((Javascript)解构对象,但对象的日期有所变化

问题描述 投票:2回答:1

我正在使用Alpha Vantage更新我正在制作的网站上的股票,因此无法解构以使date变量正常工作。 (当我放置一个静态日期时它可以正常工作,所以我知道这是问题所在。)

var today = new Date();
var date = today.getFullYear()+'-'+ pad2(today.getMonth()+1) +'-'+pad2(today.getDate());

function pad2(number) {
  return (number < 10 ? '0' : '') + number;
}

const alpha = alphavantage({ key: 'removed' });

alpha.data.daily(`msft`).then(data => {
  let {
    'Meta Data': {
      '1. Information':information,
      '2. Symbol':symbol,
      '3. Last Refreshed':lastrefreshed,
      '4. Output Size':outputsize,
      '5. Time Zone':timezone
    },
    'Time Series (Daily)': {
      date: { //breaks here
        '1. open':open,
        '2. high':high,
        '3. low':low,
        '4. close':close,
        '5. volume':volume,
      }
    }
  } = data;
  document.getElementById('stock').innerHTML = open;
});

//This is the part of the object that I need to deconstruct, the date changes every day
"Time Series (Daily)": {
  "2020-04-02": { // Where I can't get it to work
    "1. open": "105.3700",
    "2. high": "110.3200",
    "3. low": "105.1400",
    "4. close": "110.0000",
    "5. volume": "6273128"
  },
  "2020-04-01": {
    "1. open": "106.3600",
    "2. high": "109.9200",
    "3. low": "104.5210",
    "4. close": "105.1400",
    "5. volume": "6111890"
  }, //and so on
}
javascript javascript-objects destructuring alphavantage
1个回答
0
投票

使用computed property names

let data = {
  //This is the part of the object that I need to deconstruct, the date changes every day
  'Time Series (Daily)': {
    '2020-04-02': {
      // Where I can't get it to work
      '1. open': '105.3700',
      '2. high': '110.3200',
      '3. low': '105.1400',
      '4. close': '110.0000',
      '5. volume': '6273128',
    },
    '2020-04-01': {
      '1. open': '106.3600',
      '2. high': '109.9200',
      '3. low': '104.5210',
      '4. close': '105.1400',
      '5. volume': '6111890',
    }, //and so on
  },
};
var date = '2020-04-02';
let {
  'Time Series (Daily)': {
    [date]: {
      //breaks here
      '1. open': open,
      '2. high': high,
      '3. low': low,
      '4. close': close,
      '5. volume': volume,
    },
  },
} = data;

console.log({ open, high, low, close, volume });
© www.soinside.com 2019 - 2024. All rights reserved.