Home > OS >  How to iterate over JSON files
How to iterate over JSON files

Time:09-28

I am getting JSON data from two links, below is the structure of the files:

Stocks:

[{
    "id": "efcd1502-265b-4e39-9a62-d8fbd96d49bb",
    "stock_name": "AcelRx Pharmaceuticals, Inc.",
    "shareholders": [{
        "userId": "5d43449f-17a8-4747-b89a-ec2dd54b83ee",
        "number_of_shares": 378
    }, {
        "userId": "91bef464-b2ee-4c18-8d9d-0781d30a3bcb",
        "number_of_shares": 358
    }, {
        "userId": "c4a0c9ff-b934-4eda-b9fb-bd26afa21561",
        "number_of_shares": 351
    }, {
        "userId": "2a9fd876-334f-425d-9135-4211ca92a886",
        "number_of_shares": 499
    }]
}]

People:

[{
    "id": "20035a09-3820-4f49-bb8f-d947cebee537",
    "first_name": "Merell",
    "last_name": "Pecht",
    "email": "[email protected]",
    "ip_address": "159.113.166.2",
    "ssn": "819-97-0464",
    "date_of_birth": "12/12/1998",
    "address": {
        "home": {
            "street_number": "862",
            "street_name": "Starling",
            "street_suffix": "Hill",
            "city": "Riverside",
            "state": "CA",
            "zip": "92519"
        },
        "work": {
            "street_number": "3",
            "street_name": "Grayhawk",
            "street_suffix": "Circle",
            "city": "Tucson",
            "state": "AZ",
            "zip": "85710"
        }
    }
}]

Below is my code for replacing the userID present in Stocks' shareholders array with first name and last name from the people file wherever the ID matches.

require("util").inspect.defaultOptions.depth = null;
const axios = require('axios');


async function getPeople(){
    const { data } = await axios.get('https://gist.githubusercontent.com/graffixnyc/a1196cbf008e85a8e808dc60d4db7261/raw/9fd0d1a4d7846b19e52ab3551339c5b0b37cac71/people.json')
    return data // this will be the array of people objects
}  

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 a = await getPeople();
    let b = await getStocks();
    let arr = {}
    for(j=0;j<b.length;j  ){
        
        for(k=0;k<b[j].shareholders.length;k  ){
            let shareholders = []
            let res = {}
            
            for(i=0;i<a.length;i  ){
                if(b[j].shareholders[k].userId === a[i].id){
                   
                    res['first_name'] = a[i].first_name
                    res['last_name'] = a[i].last_name
                    res['number of shares'] = b[j].shareholders[k].number_of_shares
                    shareholders.push(res)
                    arr['id'] = b[j].id    
                    arr['stock_name'] = b[j].stock_name
                    arr['shareholders'] = shareholders
                    
                }
            }
        }
    }
    return arr
    
} 
async function bc(){
    const address = await listShareholders()
    console.log(address)
    } 


bc() 

The output is just one stock with the userID replaced with the name which is the last object in the stocks file. Below is the output I get. I actually need to get all of the stocks with the ID replaced. Not sure what I am doing wrong

{
  id: 'efcd1502-265b-4e39-9a62-d8fbd96d49bb',
  stock_name: 'AcelRx Pharmaceuticals, Inc.',
  shareholders: [
    {
      first_name: 'Jenni',
      last_name: 'Garrish',
      'number of shares': 499
    }
  ]
}

Code :

require("util").inspect.defaultOptions.depth = null;
const axios = require('axios');


async function getPeople(){
    const { data } = await axios.get('https://gist.githubusercontent.com/graffixnyc/a1196cbf008e85a8e808dc60d4db7261/raw/9fd0d1a4d7846b19e52ab3551339c5b0b37cac71/people.json')
    return data // this will be the array of people objects
}  

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 a = await getPeople();
    let b = await getStocks();
    b.forEach(stockItem => {
     stockItem.shareholders = stockItem.shareholders.map(shareHolderItem => {
        const person = a.find(e => e.id == shareHolderItem.userId);
        return { first_name: person?.first_name,last_name: person?.last_name,number_of_shares: shareHolderItem.number_of_shares}
     });
     
     //Keep this if you just want to show mapped shareholder only
     stockItem.shareholders = stockItem.shareholders.filter(e => e.first_name !== undefined);
    return b
  });
}
async function bc(){
    const address = await listShareholders()
    console.log(address)
    } 


bc() 

CodePudding user response:

You can do this using Spread Operator and Array.map() functions:

NOTE: I've taken the liberty to simplify the objects for the sake of the example. This should work for the original object as well

const stocks = [{
    "id": "efcd1502-265b-4e39-9a62-d8fbd96d49bb",
    "stock_name": "AcelRx Pharmaceuticals, Inc.",
    "shareholders": [{
        "userId": "1",
        "number_of_shares": 378
    }, {
        "userId": "2",
        "number_of_shares": 358
    }, {
        "userId": "3",
        "number_of_shares": 351
    }, {
        "userId": "4",
        "number_of_shares": 499
    }]
}]

const people = [{
    "id": "1",
    "first_name": "Tony",
    "last_name": "Stark",
},
{
    "id": "2",
    "first_name": "Steve",
    "last_name": "Rogers",
},
{
    "id": "3",
    "first_name": "Bruce",
    "last_name": "Banner",
},
{
    "id": "4",
    "first_name": "Thor",
    "last_name": "Odinson",
}]

const result = stocks.map(stock => {
    return {
        ...stock,
        shareholders: stock.shareholders.map(shareHolder => {
            const {first_name, last_name} = people.find(person => person.id === shareHolder.userId);
            return {
                ...shareHolder,
                first_name,
                last_name
            }
        })
    }
})

console.log(JSON.stringify(result, null, 2));

CodePudding user response:

You should use Array.map in case you want to change/map to a new structure.

const stocks = [{
  "id": "efcd1502-265b-4e39-9a62-d8fbd96d49bb",
  "stock_name": "AcelRx Pharmaceuticals, Inc.",
  "shareholders": [{
    "userId": "5d43449f-17a8-4747-b89a-ec2dd54b83ee",
    "number_of_shares": 378
  }, {
    "userId": "91bef464-b2ee-4c18-8d9d-0781d30a3bcb",
    "number_of_shares": 358
  }, {
    "userId": "c4a0c9ff-b934-4eda-b9fb-bd26afa21561",
    "number_of_shares": 351
  }, {
    "userId": "2a9fd876-334f-425d-9135-4211ca92a886",
    "number_of_shares": 499
  }, {  // my element to match to Merell Pecht
    "userId": "20035a09-3820-4f49-bb8f-d947cebee537",
    "number_of_shares": 9999
  }]
}];

const people = [{
  "id": "20035a09-3820-4f49-bb8f-d947cebee537",
  "first_name": "Merell",
  "last_name": "Pecht",
  "email": "[email protected]",
  "ip_address": "159.113.166.2",
  "ssn": "819-97-0464",
  "date_of_birth": "12/12/1998",
  "address": {
    "home": {
      "street_number": "862",
      "street_name": "Starling",
      "street_suffix": "Hill",
      "city": "Riverside",
      "state": "CA",
      "zip": "92519"
    },
    "work": {
      "street_number": "3",
      "street_name": "Grayhawk",
      "street_suffix": "Circle",
      "city": "Tucson",
      "state": "AZ",
      "zip": "85710"
    }
  }
}];

stocks.forEach(stockItem => {
   stockItem.shareholders = stockItem.shareholders.map(shareHolderItem => {
      const person = people.find(e => e.id == shareHolderItem.userId);
      return {
         first_name: person?.first_name,
         last_name: person?.last_name,
         number_of_shares: shareHolderItem.number_of_shares
      }
   });
   
   //Keep this if you just want to show mapped shareholder only
   stockItem.shareholders = stockItem.shareholders.filter(e => e.first_name !== undefined);
});

console.log(stocks);

Update: Fix function

async function listShareholders(){

    let a = await getPeople();
    let b = await getStocks();
    
    b.forEach(stockItem => {
        
     stockItem.shareholders = stockItem.shareholders.map(shareHolderItem => {
        const person = a.find(e => e.id == shareHolderItem.userId);
        return { first_name: person?.first_name,last_name: person?.last_name,number_of_shares: shareHolderItem.number_of_shares}
     });
     
     //Keep this if you just want to show mapped shareholder only
     stockItem.shareholders = stockItem.shareholders.filter(e => e.first_name !== undefined);
    
  });
  
  return b  // <- This row
}
  • Related