【问题标题】:Iterating Over Nested Object in NodeJS在 NodeJS 中迭代嵌套对象
【发布时间】:2021-05-19 22:53:20
【问题描述】:

如何迭代动态嵌套对象

{
  "2021-02-01": {
    "INR": 88.345,
    "CZK": 25.975,
    "JPY": 126.77
  },
  "2021-02-02": {
    "INR": 87.906,
    "CZK": 25.9,
    "JPY": 126.46
  },
  "2021-02-05": {
    "INR": 87.367,
    "CZK": 25.806,
    "JPY": 126.72
  }
}

注意:货币是动态的,可以更改为其他货币,例如这里是“INR, CZK, JPY”,可以更改为“USD, EUR, INR”

我需要获取对象中所有货币的所有汇率的值并将它们全部加起来

这是我的代码(它不完整,我被困在其中)

      let rates = {here is object mentioned above}
     
      //iterating over object and pushing into array rateList
      for(let keys in rates){
            rateList.push(rates[keys])
      }
      
      //iterating over rateList array to get value
      rateList.forEach((obj)=>{
          console.log(Object.keys(obj)) //by this code i'm getting keys but how do i get value and sum it up
      })

总体目标是获得所有汇率值的平均值

【问题讨论】:

    标签: javascript node.js api express object


    【解决方案1】:
    let rates = {here is object mentioned above};//main object
    
    var keys = Object.keys(rates);// Will return ["2021-02-01", "2021-02-02"]
    
    for(let i = 0; i < keys.length;i++){
      var obj = rates[keys[i]];//will return nested object. {"INR": 88.345,"CZK": 25.975,"JPY": 126.77
      }
    }
    

    【讨论】:

      【解决方案2】:

      更新答案

      根据 OP 在下面的评论,仍然有一种简写方式来完成要求:

      const rates = {
        "2021-02-01": {
          "INR": 88.345,
          "CZK": 25.975,
          "JPY": 126.77
        },
        "2021-02-02": {
          "INR": 87.906,
          "CZK": 25.9,
          "JPY": 126.46
        },
        "2021-02-05": {
          "INR": 87.367,
          "CZK": 25.806,
          "JPY": 126.72
        }
      };
      
      var returnObject = {};
      
      Object.values(rates).forEach(childObject => { // loop all child objects within parent `rates` object:
          for (const [key, value] of Object.entries(childObject)) // extract each key=>value pair
            returnObject[key] = typeof returnObject[key] === 'undefined' ? value : returnObject[key] + value; // track it in `returnObject` - checks if the currency code already exists as a key in returnObject - if so, sums the current value and all previously-encountered values - if it doesn't already exist as a key in returnObject, sets the key to the current value
      });
      
      console.dir(returnObject);

      原答案

      执行此操作的一种简写方式是:

      const rates = {
        "2021-02-01": {
          "INR": 88.345,
          "CZK": 25.975,
          "JPY": 126.77
        },
        "2021-02-02": {
          "INR": 87.906,
          "CZK": 25.9,
          "JPY": 126.46
        },
        "2021-02-05": {
          "INR": 87.367,
          "CZK": 25.806,
          "JPY": 126.72
        }
      };
      
      for (var key of Object.keys(rates)) { // loop all dates in parent `rates` object:
          rates[key] = Object.values(rates[key]).reduce((acc, cv) => acc += cv); // extract the values for all keys in the child Object into an Array, then use reduce() to sum the values; finally, replace the initial child object with the float result of the summation
      }
      console.dir(rates);

      进一步阅读:

      【讨论】:

      • 感谢您的回复@esqew,我想我的问题有误。我需要总结一种特定货币,例如给定日期范围内的 INR 总和,您的解决方案是 inr+czk+jpy 的总和,但我需要找到 2021-02-05 {inr: 82} + 2021-02 的总和-04 {inr: 82} + 2021-02-03 {inr: 82} 与其他货币一样
      • @MohammadYunus 这很有道理,请编辑您的问题以更好地反映和解释这一点。我已更新我的答案以反映这一新要求。
      • 我会更新我的问题,总结后只有一件事我怎样才能得到每个的平均值?谢谢@esqew
      【解决方案3】:

      试试吧

      let rates = {
        "2021-02-01": {
          "INR": 88.345,
          "CZK": 25.975,
          "JPY": 126.77
        },
        "2021-02-02": {
          "INR": 87.906,
          "CZK": 25.9,
          "JPY": 126.46
        },
        "2021-02-05": {
          "INR": 87.367,
          "CZK": 25.806,
          "JPY": 126.72
        }
      }
      let rateList = {};
      let avarage = {}
      //iterating over object and pushing into array rateList
      for(let keys in rates){   
         Object.keys(rates[keys]).forEach((name , index)=>{
           if(rateList[name]){
          
            rateList[name]["avg"]  = (rateList[name]["avg"] + Object.values(rates[keys])[index] )/2
            rateList[name]["sum"]  += Object.values(rates[keys])[index]
      
           }
           else{
            let obj = {}
            obj.name = name;
            obj.sum =  Object.values(rates[keys])[index];
            obj.avg = Object.values(rates[keys])[index];
            rateList[name] = obj
           }
         }) 
      }
      rateList = Object.values(rateList)
      console.log(rateList);

      【讨论】:

        【解决方案4】:

        这是一个使用object-scan的迭代解决方案

        // const objectScan = require('object-scan');
        
        const data = { '2021-02-01': { INR: 88.345, CZK: 25.975, JPY: 126.77 }, '2021-02-02': { INR: 87.906, CZK: 25.9, JPY: 126.46 }, '2021-02-05': { INR: 87.367, CZK: 25.806, JPY: 126.72 } };
        
        const aggregate = objectScan(['*.*'], {
          rtn: 'context',
          beforeFn: (state) => {
            // eslint-disable-next-line no-param-reassign
            state.context = {};
          },
          filterFn: ({ property, value, context }) => {
            if (!(property in context)) {
              context[property] = 0;
            }
            context[property] += value;
          }
        });
        
        console.log(aggregate(data));
        // => { JPY: 379.95, CZK: 77.68100000000001, INR: 263.61800000000005 }
        .as-console-wrapper {max-height: 100% !important; top: 0}
        &lt;script src="https://bundle.run/object-scan@16.0.2"&gt;&lt;/script&gt;

        免责声明:我是object-scan的作者

        【讨论】:

          猜你喜欢
          • 2016-05-30
          • 2019-01-20
          • 2022-11-15
          • 1970-01-01
          • 2018-03-08
          • 2023-03-21
          • 1970-01-01
          • 2022-12-20
          • 2020-05-04
          相关资源
          最近更新 更多