Fetching the second item within an object using JavaScript

I am trying to retrieve the data from the last month of an API, but I want to avoid hard-coding the date like this:

const data = [data.data['Monthly Time Series']['2021-11-30']]
. I need a way to dynamically access the 2nd object without specifying the date, so it always displays the actual data from the past month. Any assistance would be greatly appreciated.

This is a snippet of how the JSON structure appears:

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

Answer №1

If you want to extract an array of Monthly Time Series values, consider using Object.values().

After obtaining the monthlyTimeSeries array, you can access the second item using standard array notation ([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; }

Answer №2

If you find this a bit complex, don't worry! It simply provides the final date of your monthly records.

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 code retrieves the latest entry

Answer №3

Give it a shot

var dataResult = Object.entries(data['Monthly Time Series'])
console.log(dataResult);

Here is the outcome you'll get

[
  [
    '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'
    }
  ]
]

You can loop through this array to extract data for a specific date

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

Improved method for retrieving a subtask within a personalized grunt task?

As someone who is just starting out with Grunt and has only created a few custom grunt tasks, I've come up with what might be seen as an unconventional solution for traversing the initConfig to subtasks. My approach involves putting together a regex a ...

I noticed a change in the state between dispatches, but I did not make any alterations to the state

Although this question has been previously raised, most of the discussions focus on the OP directly mutating the state. I have taken precautions to avoid this by using techniques like the spread operator with objects and arrays. However, despite these effo ...

When I close all of my tabs or the browser, I aim to clear the local storage

Could you recommend any strategies for clearing local storage upon closing the last tab or browser? I have attempted to use local storage and session storage to keep track of open and closed sessions in an array stored in local storage. However, this meth ...

Tips on displaying tooltips on multiple graphs in Highcharts using Vue 3

I am currently utilizing vue3-highcharts in conjunction with Highcharts. My goal is to replicate a similar functionality as shown in this example: https://codepen.io/lzl124631x/pen/KLEdby?editors=1010. However, I am unsure about the correct syntax for impl ...

Transmitting information from the front-end Fetch to the back-end server

In my stack, I am using Nodejs, Express, MySQL, body-parser, and EJS. My goal is to trigger a PUT request that will update the counter by 1 when a button is pressed. The idea is to pass the ID of the clicked button to increment it by 1. app.put("/too ...

What is the best way to create a case-insensitive search feature in Node.js?

I have implemented a search function that takes input from the client as Str. If it matches with content in a file, I send that response. For example, if I have text in a file labeled Lorem, and the client searches for lorem, it returns an empty array due ...

Is there a way to retrieve the sub-child menu data from a JSON file?

I am currently working on creating a horizontal menu from a json file. However, I am facing issues in retrieving the subchild elements properly. Below is an example of my json file: var data = [{ "menu":[ { "MenuId":1, ...

After reloading the page, Nuxt dynamic routes are displaying a 404 error

Hey there! I'm currently diving into a project that involves using nuxt js, and it's all new to me. I've set it up in spa mode without any modifications in the nuxt config file, just sticking with the default settings. Here's how I&apos ...

Determining the time gap in milliseconds between two specified times using the "DD/MM/YYYY HH:mm:ss:ms" format in JavaScript

I have a situation where I need to calculate the time difference between two timestamps. Starting time: "2014/10/28 11:50:28:318" Ending time: "2014/10/28 11:50:35:249" To achieve this, I utilized moment.js for the calculation. Here is my code: var msE ...

Tips for integrating the AJAX response into a Sumo Select dropdown menu

I am currently using Sumoselect for my dropdowns, which can be found at . The dropdowns on my page are named as countries, state, and cities. The countries are shown in the dropdown, and based on the country selected, the corresponding state name should a ...

Troubleshooting the sidebar pin-unpin problem using Jquery and CSS

I have created a single side panel that allows me to toggle between opening and closing the sidebar by hovering on it. I can also pin and unpin the sidebar by clicking on the pin image. Now, I want to open the sidebar onClick instead of onHover and remove ...

Distinguishing Between server.listen() and app.listen() in Google Apple Engine

I am currently working on a NodeJS + Express application. While running it locally, I have the following code: const port = 3001; server.listen(port, () => { console.log(`App listening on port ${port}`); }); However, when deploying to GAE, I switch ...

Send a request from my own local client without encountering any Cross-Origin Resource Sharing (C

I am attempting to send a request from my locally hosted Node.js/Express.js client to a third-party API that I have deployed on the cloud. Strangely, I keep running into a CORS error whenever I make the request. The interesting part is that the request wor ...

What is the process for modifying JSON attributes with JavaScript?

One JSON data set is provided below: [{ ID: '0001591', name: 'EDUARDO DE BARROS THOMÉ', class: 'EM1A', 'phone Pai': '(11) 999822922', 'email Pai': '<a href="/cdn-cgi/l/em ...

Switch or toggle between colors using CSS and JavaScript

Greetings for taking the time to review this query! I'm currently in the process of designing a login form specifically catered towards students and teachers One key feature I'm incorporating is a switch or toggle button that alternates between ...

Is it possible to render the v-for value dynamically?

I have a dynamic component and I'm trying to iterate through different objects from it. However, my current code isn't working as intended. Can someone please guide me on how to make the activeQuestion value in v-for dynamic? Thank you for your a ...

What is the best way to modify the state of a particular element in an array when using useState in React?

In my Next.js application, I am using a useState hook to manage state. Here is how my initial state looks like: const [sampleData, setSampleData] = useState({ value1: '', value2: '', value3: [] }); To update the state ...

Exploring new classes with jQuery's .not() and :not()?

I am working on a memory game where I need to flip cards and check if two are equal. My issue is that I do not want the function to run when clicking on a card that is already flipped, or on another flipped card. I tried using jQuery's .not() and :no ...

The React Native Expo is throwing an error stating that it is unable to locate the module 'minizlib'

At the instructions available in the read.me of https://github.com/react-community/create-react-native-app Upon selecting my template using the expo init command, I encountered the following error: Cannot find module 'minizlib' Error: Cannot fi ...