(Javascript) Деконструкция объекта, но дата изменения объекта - PullRequest
3 голосов
/ 03 апреля 2020

Я использую Alpha Vantage для обновления акций на создаваемом мной веб-сайте, и я не могу заставить деконструкцию работать должным образом с переменной даты. (Это работает правильно, когда я помещаю дату c, поэтому я знаю, что это проблема.)

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
}

1 Ответ

2 голосов
/ 03 апреля 2020

Использовать вычисленные имена свойств :

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 });
...