Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript – How to access second object of an object

I need to access the last month data of an API, but I don’t know how could I access the 2nd object, without hard coding the date like so:
const data = [data.data['Monthly Time Series']['2021-11-30']]. In this example currently I would need the November data from the ‘Monthly Time Series’, but I need it to be dynamic instead of writing out the date, so it will always show the actual past month data. I would appreciate any help.

This is how the JSON looks like:

{
  "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"
    },

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This might look a little complicated but it definetely gives you the last date of your Monthly entries

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading