Home > Enterprise >  How to access the data from JSON
How to access the data from JSON

Time:09-25

I'm accessing values of an object within an array within an object. Below is the format of the data:

 [{
    "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
    }]
}]

Below is my code to get data from github using axios and print out 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()

Not sure why I get no output.

CodePudding user response:

Edited

I'm editing to include the code from the original answer (not posted by me) that disappeared

At for(j=0;j<a[i].shareholders;j ) you are comparing a number with an Array. This is the proper code:

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

My Answer

As pointed out at for(j=0;j<a[i].shareholders;j ) you are comparing a number with an Array.

The proposed solution works, but keep in mind that you can do it in one line:

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