What is the best way to loop through a nested object and extract values into an array?

I'm currently working on extracting data points from an API response to use in graphing. My goal is to extract an array of the "4. close" values from the object below.


let res = {
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "amzn",
        "3. Last Refreshed": "2020-03-20",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2020-03-20": {
            "1. open": "1926.3100",
            "2. high": "1957.0000",
            "3. low": "1820.7300",
            "4. close": "1846.0900",
            "5. volume": "9740990"
        },
        "2020-03-19": {
            "1. open": "1860.0000",
            "2. high": "1945.0000",
            "3. low": "1832.6500",
            "4. close": "1880.9300",
            "5. volume": "10399943"
        },
        "2020-03-18": {
            "1. open": "1750.0000",
            "2. high": "1841.6600",
            "3. low": "1745.0000",
            "4. close": "1830.0000",
            "5. volume": "9596297"
        }
    }
}

// Desired output => [1846, 1880, 1830]

Here's my current code:

const parsed = res["Time Series (Daily)"]

const datesArr = Object.entries(parsed).map((e) => ({ [e[0]]: e[1] }))


function getYCoords() {
  for(i=0;i<datesArr.length;i++) {
  let dateObj = datesArr[i]
  console.log(dateObj["4. close"])
  }
}


I attempted to map the nested object into an array of objects, thinking it would help me iterate through the data correctly, but I seem to be facing issues as I am getting undefined values. Any assistance would be greatly appreciated!

Answer №1

One issue you are facing is that Object.entries(parsed) returns an array structured like this:

[ "2020-03-20", { "1. open": "1926.3100", "2. high": "1957.0000", "3. low": "1820.7300", "4. close": "1846.0900", "5. volume": "9740990" } ], [ "2020-03-19", { "1. open": "1860.0000", "2. high": "1945.0000", "3. low": "1832.6500", "4. close": "1880.9300", "5. volume": "10399943" } ], [ "2020-03-18", { "1. open": "1750.0000", "2. high": "1841.6600", "3. low": "1745.0000", "4. close": "1830.0000", "5. volume": "9596297" } ] ]

By mapping e[0] as the key of a new object, you're assigning the date as the key instead of the properties like "4. close" from your objects. An easy solution would be to map the entries to the object stored at e[1], which contains all the numbered properties:

const res = { "Meta Data": { "1. Information": "Daily Prices (open, high, low, close) and Volumes", "2. Symbol": "amzn", "3. Last Refreshed": "2020-03-20", "4. Output Size": "Compact", "5. Time Zone": "US/Eastern" }, "Time Series (Daily)": { "2020-03-20": { "1. open": "1926.3100", "2. high": "1957.0000", "3. low": "1820.7300", "4. close": "1846.0900", "5. volume": "9740990" }, "2020-03-19": { "1. open": "1860.0000", "2. high": "1945.0000", "3. low": "1832.6500", "4. close": "1880.9300", "5. volume": "10399943" }, "2020-03-18": { "1. open": "1750.0000", "2. high": "1841.6600", "3. low": "1745.0000", "4. close": "1830.0000", "5. volume": "9596297" } } }
const parsed = res["Time Series (Daily)"];


function getYCoords() {
  for (i = 0; i < datesArr.length; i++) {
    let dateObj = datesArr[i]
    console.log(dateObj["4. close"])
  }
}

const datesArr = Object.entries(parsed).map((e) => e[1]);
getYCoords();

However, if you are only interested in the values, there's no need to use entries. You can directly get the Object.values() (an array of your objects) and then map those to retrieve the values stored at "4. close":

const res = { "Meta Data": { "1. Information": "Daily Prices (open, high, low, close) and Volumes", "2. Symbol": "amzn", "3. Last Refreshed": "2020-03-20", "4. Output Size": "Compact", "5. Time Zone": "US/Eastern" }, "Time Series (Daily)": { "2020-03-20": { "1. open": "1926.3100", "2. high": "1957.0000", "3. low": "1820.7300", "4. close": "1846.0900", "5. volume": "9740990" }, "2020-03-19": { "1. open": "1860.0000", "2. high": "1945.0000", "3. low": "1832.6500", "4. close": "1880.9300", "5. volume": "10399943" }, "2020-03-18": { "1. open": "1750.0000", "2. high": "1841.6600", "3. low": "1745.0000", "4. close": "1830.0000", "5. volume": "9596297" } } }
const parsed = res["Time Series (Daily)"];
const datesArr = Object.values(parsed).map((e) => +e["4. close"]); // + to turn string into number
console.log(datesArr);

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

The watch functionality is failing to work within a specialized attribute directive that is being utilized within a separate custom element directive

I'm currently working with two directives that handle separate functionalities. I am attempting to utilize the attribute directive within an element directive, but I'm encountering issues with the watch function not working on the attribute direc ...

Stop the WebGL Three.js container from capturing scroll events

I am working on a full-screen three.js application which serves as the background and I am trying to add overlaid text that can be scrolled. However, my issue arises from the fact that the three.js WebGL container intercepts all scroll events and prevents ...

Is Cognito redirect causing issues with Angular router responsiveness?

When employing social login via AWS Cognito, Cognito sends a redirect to the browser directing it to the signin redirect URL after signing in. In this case, the specified URL is http://localhost:4200/home/. Upon receiving this redirect, the application in ...

Looking for assistance with implementing the Vue CDN script in a Laravel Blade template

Hey everyone, currently I am working on a project called Register Page. My goal is to incorporate Vue cdn and Vue Consoles within the blade template. I have implemented a show/hide option without any console errors appearing. However, when I click on the ...

Generatively generating a new element for the react application to be mounted on

I am looking to enhance my JavaScript application using React by creating a build. Currently, the application consists of just a single file structured as follows. This file essentially creates a div element and continuously changes the color of the text & ...

Utilizing Ajax to dynamically load files within the Django framework

My current project involves working with Django, specifically a feature that requires loading a file and displaying its content in a textarea. Instead of storing the file on the server side or in a database, I am exploring the use of AJAX to send the file ...

Accept a JSON-sending POST request in a JSP file via JavaScript

I have developed an HTML page with an input field. Using javascript, I extract the input value, convert it into JSON format, and attempt to send it through ajax. Additionally, I have a JSP application where a Java method processes this JSON data to store i ...

Unable to upload any further verification documents to Stripe Connect bank account in order to activate payouts

Query - Which specific parameters should I use to generate the correct token for updating my Stripe bank account in order to activate payouts? I've attempted to activate payouts for my Stripe bank account by using a test routing and account number (t ...

What steps can I take to stop the window/body from scrolling "through" a modal div?

Let me simplify my layout for you: <body> [... lots of content ...] <div id="modal-overlay"> </div> </body> The body has so much content that the whole page scrolls. The styling for #modal-overlay looks like this: #m ...

"Socket io Simplified: Embracing the Power of Drag

I'm currently in the process of developing a multiplayer card game using node, express, and socket io. However, I am facing some difficulties when it comes to transmitting drag and drop actions performed by one player to another connected player' ...

Every initial test with Protractor ends in failure

Here are the versions I am currently using: protractor v5.1.2 chromedriver v2.33 node v6.11.4 npm 3.10.10 selenium-webdriver v3.0.1 I am a beginner with protractor and I am attempting to run the provided test natively included in protractor. The test scr ...

Choose an XPath formula that will target every single element, text node, and comment node in the original sequence

How can we write an XPath expression that selects all elements, text nodes, and comment nodes in the order they appear in the document? The code below selects all elements but not text nodes and comment nodes: let result = document.evaluate('//*&apo ...

Use the on-screen keyboard to move around by using the arrow keys and choose a value from the list to

I am currently working on developing an on-screen keyboard that allows for navigation using arrow keys and selection with the enter key. My goal is to have each selected key append to an input field. Below is the HTML code I have implemented: <div id ...

Creating an Angular form that adapts to changing input values

I'm encountering a problem with angular not recognizing the dynamic values from my inputs. My objective is to have angular populate hidden form fields with lat/lon when a user clicks on the map. The user then submits the form, but the data ends up mi ...

How to implement caching using XMLHttpRequest?

As someone who has primarily relied on jQuery's AjAX method, I am relatively new to using XMLHttpRequests. However, due to performance concerns in a web worker environment, I now find myself having to resort to the classic XMLHttpRequest. Currently, ...

a function that repeats every single second

A challenge I am facing is creating a countdown timer with a time that refreshes every second. My current implementation uses setInterval, but it only seems to run once instead of every second. Can anyone help me identify the issue in my code? var countDo ...

Bootstrap allows for the use of video backgrounds, offering the option for borders to be included

Having trouble with a Bootstrap HTML page featuring a video background? The issue is that sometimes the video has borders on the left and right, and occasionally on mobile devices as well. Oddly enough, when the browser (Chrome or Firefox) is refreshed, th ...

Testing the seamless integration of Mocha, Node.js, and PostgreSQL

I have been struggling with this issue for quite some time now. After researching online and checking out various resources like the internet and StackOverflow, I couldn't find a solution that fits my requirements. To tackle the problem, I decided to ...

Arrange the HTML DOM elements in the order of their appearance in a list

Is it possible to rearrange the order of <div> and its elements based on database information? For example, consider the following HTML structure: <div id="container"> <div id="A"> Form elements for A</div> <div id="B"& ...

Achieving automatic restarts with grunt-express when files are updated

I am working on implementing grunt-express and grunt-watch in my project. My goal is to have the server automatically reload whenever I make changes to my server file. Below is the setup I currently have: Gruntfile.js var path = require('path' ...