【问题标题】:How to iterate over JSON files如何遍历 JSON 文件
【发布时间】:2021-11-19 06:21:31
【问题描述】:

我从两个链接获取 JSON 数据,以下是文件结构:

股票:

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

人:

[{
    "id": "20035a09-3820-4f49-bb8f-d947cebee537",
    "first_name": "Merell",
    "last_name": "Pecht",
    "email": "mpecht0@uol.com.br",
    "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 的股东数组中的用户 ID 替换为 ID 匹配的人员文件中的名字和姓氏。

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() 

输出只是一只股票,用户ID 被替换为股票文件中最后一个对象的名称。下面是我得到的输出。我实际上需要得到所有替换了 ID 的股票。不知道我做错了什么

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

代码:

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() 

【问题讨论】:

    标签: javascript json async-await axios javascript-objects


    【解决方案1】:

    您应该使用Array.map 以防您想更改/映射到新结构。

    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": "mpecht0@uol.com.br",
      "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);

    更新:修复功能

    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
    }
    

    【讨论】:

    • 当我将它添加到我的 listShareholders 函数时,它返回未定义。当我运行调试器时,它不会进入 return 语句
    • @swombhai 你能展示你的代码吗?你如何与我的代码集成?
    • 我已在我原来的问题中添加了您的代码,代码如下:cmets dont let me paste it here
    • @swombhai 你在错误的行在function listShareholders() 中返回b,我用固定函数编辑了我的答案。希望对您有所帮助。
    【解决方案2】:

    您可以使用扩展运算符和Array.map() 函数来做到这一点:

    注意:为了示例,我冒昧地简化了对象。这也适用于原始对象

    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));

    【讨论】:

    • 这很有帮助,谢谢,有没有办法可以从显示中删除 userId,因为我必须用名称替换 id
    • 是的。您可以更改内部返回以适合您的用例
    猜你喜欢
    • 2011-11-29
    • 2020-06-12
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多