首页 > 解决方案 > 在 NodeJS 中迭代嵌套对象

问题描述

如何迭代动态嵌套对象

{
  "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
      })

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

标签: javascriptnode.jsapiexpressobject

解决方案


更新的答案

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

进一步阅读:


推荐阅读