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

unable to transform this string into an object

https://i.sstatic.net/O46IL.pngWhy am I encountering difficulties converting this string into an object? Any assistance on resolving this error would be greatly appreciated. onSignup(data:any){ localStorage.setItem('users',JSON.string ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

What could be causing my JavaScript code to fail to add data when the submit button is

I'm currently working on a Hot and Cold App using JS and jQuery. The problem I'm facing is that upon form submission, the user input inserts a number, and the game should provide feedback by telling them if it's hot, cold, hotter, or colder ...

PHP and JavaScript are two powerful programming languages that are

While I understand that PHP and JavaScript operate in different locations, I am curious to know if there is a way to incorporate some PHP code into my JavaScript file. I need to create unique URLs for linking to profiles and news posts, such as /#/news/IDH ...

Adapting iFrame height to accommodate fluctuating content height in real time (details included)

I have an embedded iframe that contains a form with jQuery validation. When errors occur, the content height of the iframe increases dynamically. Below is the script I use to adjust the height of my iframe based on its content: function doIframe(){ o = d ...

What is the method for obtaining a date in the format of 2018-05-23T23:00:00.000+00:00?

Recently, I've been attempting to filter data based on dates in my database. The format in which the dates are saved is as follows: 2018-05-23T23:00:00.000+00:00 This was my initial approach: router.get('/byDate', function (req, res) { ...

Exploring Three.js on Cordova with WebGL

I am working on developing a mobile app using Three.js on Cordova. While the app runs smoothly on a PC browser, it encounters an issue when trying to create the WebGL context on a Samsung Note 3 device. The specific error message is: THREE.WebGLRenderer ...

Guide on sending AJAX requests from Javascript/React to Python REST API and receiving data

In my project, I have developed the front end code using React. There is a simple form where users can input their name, title, department, and other basic string fields. Upon hitting submit, JavaScript triggers an AJAX request to my REST API which is impl ...

Malfunctioning JavaScript timepiece

I am currently experimenting with using Raphael to create a unique clock feature on my website. My goal is to animate the seconds hand to mimic the movement of a traditional clock. Below is the code snippet I have implemented: window.onload = function( ...

Mapbox GL - Incorporate a non-scaling polygon feature during zoom operations

Is there a method to incorporate a polygon that maintains its size regardless of zooming? Currently, when adding a polygon circle shape with a 10-meter radius and zooming out, the polygon shrinks in size as expected. However, is it feasible to include a s ...

Creating a button that integrates an image within a single div element

Currently, I understand the code: $('#leftDev').css("background-image", "url(img/1.png) "); will set the entire background of my leftDiv to display "1.png". However, I would like to position this image as a regular picture within the div and no ...

Struggling to delete a specific item by its ID from MongoDB within a Next.js application

Currently, I am building a todo app in nextjs to enhance my skills. However, I'm encountering some difficulties in deleting single todos from the database using the deleteOne function. Below is the frontend call: async function deleteTodo(id) { a ...

the router is having trouble choosing the right function

When attempting to log in a user using postman with the URL http://localhost:3000/login, it seems to always trigger the register function instead. The code itself is working fine, but it's just routing to the wrong function. How can I redirect it to t ...

Distance Calculator for Geolocation WatchPosition

I am currently utilizing geolocation to track the user's current location and keep an eye on it using the watchPosition method. Is there a way to determine the distance between the starting position of the user and their current position? Here is the ...

Accessed a property that is not defined on the instance during rendering

One of the components I'm working on displays data that is defined in the component's state. To access this data, I created a getter: export default createStore({ state: { foo: true, }, getters: { getFoo: state => state.fo ...

Utilizing a dictionary for comparing with an API response in order to generate an array of unique objects by eliminating duplicates

I currently have a React component that utilizes a dictionary to compare against an API response for address state. The goal is to map only the states that are returned back as options in a dropdown. Below is the mapping function used to create an array o ...

Place an image at the top of the canvas at a specific location

Currently, I am in the process of reconstructing this specific website My approach involves working with React (similar to the aforementioned site) and utilizing the same cropper tool that they have implemented. For cropping, I am incorporating react-imag ...

Ensure to close the Ajax request from PHP before the script finishes executing

Is there a way to terminate an Ajax request from PHP before the script finishes executing? For instance, if a user requests php.php and it includes the line 'echo "phpphp"', how can we ensure that the Ajax request is completed with the data "phpp ...

Encountering Uncaught Syntax Error when attempting a request with JSON parameters

Currently, I am using Fetch to send a post request to my server while including some additional information. Here's the code snippet: var rating = document.getElementById("rating"); var ratingValue = rating.innerHTML; fetch("/films",{ method: "po ...

Angular unable to send object to HTML page

Struggling with learning angular, encountering new challenges when working with objects in different components. In two separate instances, try to implement two different mechanisms (microservice or service component serving an object directly). This speci ...