Ways to retrieve information from JSON

I am currently trying to access the values of an object that is within an array which is inside another object. The data is structured as follows:

 [{
    "id": "99a4e6ef-68b0-4cdc-8f2f-d0337290a9be",
    "stock_name": "Just Energy Group, Inc.",
    "shareholders": [{
        "userId": "e9328bb2-81ac-4e86-9ec8-520b1909cc9b",
        "number_of_shares": 266
    }, {
        "userId": "d42ff6a6-9b2f-4561-ac2e-0cf2bb170430",
        "number_of_shares": 389
    }]
}]

The following is the code I am using to retrieve data from GitHub using axios and display the user ID:

const axios = require('axios')
require("util").inspect.defaultOptions.depth = null;
async function getStocks(){
    const { data } = await axios.get('https://gist.githubusercontent.com/graffixnyc/8c363d85e61863ac044097c0d199dbcc/raw/7d79752a9342ac97e4953bce23db0388a39642bf/stocks.json')
    return data // this will be the array of people objects
}
async function listShareholders() {
    let c=[]
    let a = await getStocks();
    for(i=0;i<a.length;i++){
        for(j=0;j<a[i].shareholders;j++)
            c.push((a[i].shareholders[j].userId))
    }
    return c 
    
}
async function bc(){
    const address = await listShareholders()
    console.log(address)
} 

bc()

I am unsure why I am not getting any output.

Answer №1

Modified

I have made some edits to include the code snippet from the original answer (which was not authored by me) that went missing.

Within the line

for(j=0;j<a[i].shareholders;j++)
, you are mistakenly comparing a number with an Array. The corrected code should look like this:

for(i=0;i<a.length;i++){
     for(j=0; j < a[i].shareholders.length; j++)
         c.push((a[i].shareholders[j].userId);
}

My Response

It has been noted that at

for(j=0;j<a[i].shareholders;j++)
, there is a comparison error between a number and an Array.

The solution provided is effective; however, it can be simplified into a single line of code:

const c = a.flatMap(obj => obj.shareholders.map(s => s.userId));

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

Troubleshoot React component re-rendering issue

I'm currently facing a challenging bug that only occurs very sporadically (about once every few dozen attempts). During the render call, I'm determined to gather as much information as possible: I want to understand what triggered the rerender ...

Iterate through JSON data and access values based on keys using a $.each loop

I have retrieved JSON data from the controller using AJAX and now I want to access this data. The data is in the form of a list of objects (array) with key-value pairs, so I am planning to use .each() function to go through all the data. The array looks li ...

Problem with the WP Rocket helper plugin that excludes JS scripts from Delay JS only at specific URLs

Looking for assistance with a helper plugin that excludes scripts from "Delay Javascript Execution"? You can find more information about this plugin here. The specific pages where I want to exclude slick.min.js and jquery.min.js are the home page and tabl ...

Async Autocomplete fails to display options if the label keys do not match the filtering keys

While I have experience with ReactJs and Material UI, I encountered a surprising issue. I am using the Material-UI Autocomplete component as shown below. The users variable is an array of objects. When searching for firstName or lastName in the user table, ...

Creating a nested object in Node.js using parent IDs

During my internship, I have been tasked with constructing a nested object using parent IDs without utilizing a children attribute array. Initially, I employed the npm package flatnest for a single-level hierarchy; however, the challenge lies in adapting t ...

I must design a unique layout for my website

I am creating a webpage with various shapes and elements. However, I am facing a challenge with creating a shape that is commonly used. In platforms like Khan Academy, there is simulated programming where shapes can be easily created with a simple command ...

Choosing a Query with Puppeteer - Unleashing the Power of Selection in Puppeteer

How do I use Puppeteer to select the html anchor element that clicks and navigates to the Tutorial page? https://i.sstatic.net/6rkNn.png I've tried this but it's not working const puppeteer = require('puppeteer'); const url = process ...

Leveraging environment variables within package.json

Working on an older application, I've encountered a challenge where the API endpoint URL varies depending on the system. Currently, my package.json file looks like this: "start": "cross-env API_ENDPOINT=http://localhost:5000/api/v1 react-scripts sta ...

Include an extra "array" in the complete AJAX POST data when submitting through x-editable

Struggling to include an array of objects in the post data for a group of bootstrap x-editable on my JSP page. The data is retrieved from a table and an array of objects is constructed. This array needs to be appended to the list of other values posted by ...

Changes in query parameters on NextJS navigation within the same page do not activate hooks

When utilizing NextJS without SSR, I encountered an issue with basic navigation using different query parameters. Upon the initial arrival on the page/component, everything seems fine as the component gets mounted and URL params change accordingly. However ...

Tips for combining data from various sources in GraphQL

Need some guidance on setting up GraphQL as a beginner. I am facing challenges in efficiently setting up resolvers for my schema, especially when dealing with fields from different backend APIs. type User { name: String address: String dateOfBirth ...

Why is it that in IE9, submitting a basic form using jQuery doesn't seem to work?

Take a look at the code snippet below: <html> <head> <style type="text/css"> #myform {display:none;} </style> </head> <body> <button type="button" id="uploadbutton">Upload Images</button> <form name="myf ...

Exploring ways to retrieve boolean values with Angular and PHP

I am currently learning Angular and PHP and I am trying to make some modifications to the tutorial found at . Specifically, I want to change the second value to a checkbox and retrieve its value using both Angular and PHP. However, I am encountering an iss ...

How to troubleshoot Props not functioning in nextjs-typescript?

I'm having trouble with props in my project and I can't seem to figure it out! Here are the three files. I'm still learning typescript but everything seems fine in the code, yet it's not working! Here is index.tsx file: const Home: ...

Ensuring object validation with JSON schema in C#

In my C# API, I am experimenting with using a JSON schema to validate an incoming object parameter. Here is the prototype of my API: void BuildSqlQueryFromSegment(JoinDefinition jsonDef); The JoinDefinition object is complex, with many interdependent pro ...

Enhance your image viewing experience with a React component that smoothly zooms in on images without distorting their dimensions, all with

After searching extensively for a solution, I have been unable to find one that works. My current setup involves using React with Bootstrap. I am in need of a stateless functional component that can take an image path as input and return an img element. Th ...

Transform JSON data into a new object

I'm currently exploring methods to manipulate my JSON data and create a separate object with the modified information. Specifically, I am working with this JSON file: My goal is to transform [dataset][data] into the following format: [Date.UTC(2013 ...

After successfully sending a GET request to the API, the Next.js 13.4.3 website still does not reflect new posts added on the hosting platform

I am currently using Next.js version 13.4.3 in my app directory to create a blog site. However, I am facing an issue. When I run npm run build locally on my computer and then start with npm run start, the new posts are displayed normally after adding them ...

Retrieving the selected value from a dropdown menu without having to click on a

I'm facing an issue with 2 dropdown menus outside of an HTML table that is generated by PHP code. There's a submit button within this table, and here's how it's set up: <!doctype html> Select Year: ...

Process for evaluating information before storing in database: MongoDB

The concept behind the application is to display all "E-number" ingredients found in a product (such as E100 and E200). Let's consider a scenario where we have a variety of products being added to our database (via JSONs, web scraping, or APIs). Each ...